From caba96ef557464283b983466e5e490f3545d8c41 Mon Sep 17 00:00:00 2001 From: Jonas Date: Thu, 16 Dec 2021 15:18:01 +0100 Subject: [PATCH] ref(types): deprecate severity enum (#4280) * fix(types): use SeverityLevel * fix(types): remove other references to the enum * fix(types): disable deprecation warning * fix(types): move fromString to utils * packages(types): fix exports * fix(rebase): fix conflicts * ref(types): deprecate status enum (#4298) * ref(types): deprecate enum and export type * ref(types): fix fromHttpCode usage to statusFromHttpCode * ref(types): remove enum usage * fix(types): fix mistake on span * fix: fmt * ref(types): do not export the status enum * ref(types): fix all imports * ref(utils): consistent naming * ref(types): deprecate span status enum (#4299) * ref(span): deprecate span status enum * ts(span): widen type * ref(span): avoid reexporting the enum * ref(types): fix all imports * fix(test): remove extra space * fix(test): import extension methods * ref(types): deprecate transactionmethod enum (#4314) * ref(types): deprecate transactionmethod enum * fix(types): drop transactionsamplingmethod * ref(types): deprecate outcome enum (#4315) * ref(types): deprecate outcome enum * fix(types): drop transportoutcome * ref(types): deprecate request status enum (#4316) * ref(types): deprecate request status * ref(types): deprecate session status * ref(types): remove unused logLevel (#4317) (#4320) Co-authored-by: Armin Ronacher Co-authored-by: Armin Ronacher --- packages/browser/src/backend.ts | 4 +- packages/browser/src/eventbuilder.ts | 6 +- packages/browser/src/exports.ts | 4 +- .../browser/src/integrations/breadcrumbs.ts | 7 +- .../src/integrations/globalhandlers.ts | 4 +- packages/browser/src/transports/base.ts | 6 +- packages/browser/src/transports/fetch.ts | 8 +- packages/browser/src/transports/xhr.ts | 8 +- .../test/unit/mocks/simpletransport.ts | 6 +- .../browser/test/unit/transports/base.test.ts | 32 +++---- .../test/unit/transports/fetch.test.ts | 35 ++++--- .../browser/test/unit/transports/xhr.test.ts | 33 ++++--- packages/core/src/basebackend.ts | 6 +- packages/core/src/baseclient.ts | 16 ++-- packages/core/src/transports/noop.ts | 4 +- packages/core/test/lib/base.test.ts | 10 +- packages/core/test/lib/request.test.ts | 10 +- packages/core/test/mocks/backend.ts | 4 +- packages/core/test/mocks/transport.ts | 4 +- packages/hub/src/hub.ts | 9 +- packages/hub/src/scope.ts | 6 +- packages/hub/src/session.ts | 8 +- packages/hub/src/sessionflusher.ts | 6 +- packages/hub/test/scope.test.ts | 52 +++++----- packages/hub/test/session.test.ts | 22 ++--- packages/hub/test/sessionflusher.test.ts | 26 +++-- packages/integrations/src/captureconsole.ts | 6 +- packages/minimal/src/index.ts | 6 +- packages/minimal/test/lib/minimal.test.ts | 17 ++-- packages/node/src/backend.ts | 4 +- packages/node/src/client.ts | 10 +- packages/node/src/handlers.ts | 9 +- packages/node/src/index.ts | 4 +- packages/node/src/integrations/console.ts | 23 +---- .../src/integrations/onuncaughtexception.ts | 4 +- packages/node/src/sdk.ts | 2 +- packages/node/src/transports/base/index.ts | 7 +- packages/node/test/client.test.ts | 37 ++++---- packages/node/test/handlers.test.ts | 22 ++--- packages/node/test/transports/http.test.ts | 32 +++---- packages/serverless/src/awslambda.ts | 3 +- packages/tracing/src/browser/backgroundtab.ts | 8 +- .../tracing/src/browser/browsertracing.ts | 3 +- packages/tracing/src/browser/request.ts | 3 +- packages/tracing/src/errors.ts | 7 +- packages/tracing/src/hubextensions.ts | 9 +- packages/tracing/src/idletransaction.ts | 5 +- packages/tracing/src/index.bundle.ts | 4 +- packages/tracing/src/index.ts | 3 +- packages/tracing/src/span.ts | 94 +++++++++++++++++-- packages/tracing/src/spanstatus.ts | 49 ---------- packages/tracing/src/transaction.ts | 3 +- .../test/browser/backgroundtab.test.ts | 7 +- .../test/browser/browsertracing.test.ts | 3 +- packages/tracing/test/browser/request.test.ts | 6 +- packages/tracing/test/errors.test.ts | 5 +- packages/tracing/test/hub.test.ts | 9 +- packages/tracing/test/idletransaction.test.ts | 14 ++- packages/tracing/test/span.test.ts | 10 +- packages/types/src/breadcrumb.ts | 4 +- packages/types/src/client.ts | 4 +- packages/types/src/event.ts | 4 +- packages/types/src/eventstatus.ts | 13 +++ packages/types/src/hub.ts | 4 +- packages/types/src/index.ts | 6 +- packages/types/src/loglevel.ts | 11 --- packages/types/src/options.ts | 4 - packages/types/src/requestsessionstatus.ts | 11 +++ packages/types/src/response.ts | 4 +- packages/types/src/scope.ts | 6 +- packages/types/src/session.ts | 24 +---- packages/types/src/sessionstatus.ts | 13 +++ packages/types/src/severity.ts | 36 +------ packages/types/src/status.ts | 34 +------ packages/types/src/transaction.ts | 9 +- packages/types/src/transport.ts | 15 ++- packages/utils/src/index.ts | 2 + packages/utils/src/severity.ts | 18 ++++ packages/utils/src/status.ts | 26 +++++ packages/utils/test/severity.test.ts | 24 +++++ packages/vue/src/index.bundle.ts | 4 +- 81 files changed, 526 insertions(+), 514 deletions(-) create mode 100644 packages/types/src/eventstatus.ts delete mode 100644 packages/types/src/loglevel.ts create mode 100644 packages/types/src/requestsessionstatus.ts create mode 100644 packages/types/src/sessionstatus.ts create mode 100644 packages/utils/src/severity.ts create mode 100644 packages/utils/src/status.ts create mode 100644 packages/utils/test/severity.test.ts diff --git a/packages/browser/src/backend.ts b/packages/browser/src/backend.ts index 88d0bba7bc75..5396a8b3dab6 100644 --- a/packages/browser/src/backend.ts +++ b/packages/browser/src/backend.ts @@ -1,5 +1,5 @@ import { BaseBackend } from '@sentry/core'; -import { Event, EventHint, Options, Severity, Transport } from '@sentry/types'; +import { Event, EventHint, Options, SeverityLevel, Transport } from '@sentry/types'; import { supportsFetch } from '@sentry/utils'; import { eventFromException, eventFromMessage } from './eventbuilder'; @@ -45,7 +45,7 @@ export class BrowserBackend extends BaseBackend { /** * @inheritDoc */ - public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike { + public eventFromMessage(message: string, level: SeverityLevel = 'info', hint?: EventHint): PromiseLike { return eventFromMessage(this._options, message, level, hint); } diff --git a/packages/browser/src/eventbuilder.ts b/packages/browser/src/eventbuilder.ts index 2a741e5f5a1d..afc7b51c50d1 100644 --- a/packages/browser/src/eventbuilder.ts +++ b/packages/browser/src/eventbuilder.ts @@ -1,4 +1,4 @@ -import { Event, EventHint, Options, Severity } from '@sentry/types'; +import { Event, EventHint, Options, SeverityLevel } from '@sentry/types'; import { addExceptionMechanism, addExceptionTypeValue, @@ -24,7 +24,7 @@ export function eventFromException(options: Options, exception: unknown, hint?: attachStacktrace: options.attachStacktrace, }); addExceptionMechanism(event); // defaults to { type: 'generic', handled: true } - event.level = Severity.Error; + event.level = 'error'; if (hint && hint.event_id) { event.event_id = hint.event_id; } @@ -38,7 +38,7 @@ export function eventFromException(options: Options, exception: unknown, hint?: export function eventFromMessage( options: Options, message: string, - level: Severity = Severity.Info, + level: SeverityLevel = 'info', hint?: EventHint, ): PromiseLike { const syntheticException = (hint && hint.syntheticException) || undefined; diff --git a/packages/browser/src/exports.ts b/packages/browser/src/exports.ts index cbe5c0c4f262..60cce87af08a 100644 --- a/packages/browser/src/exports.ts +++ b/packages/browser/src/exports.ts @@ -5,12 +5,12 @@ export { SdkInfo, Event, EventHint, + EventStatus, Exception, Response, - Severity, + SeverityLevel, StackFrame, Stacktrace, - Status, Thread, User, } from '@sentry/types'; diff --git a/packages/browser/src/integrations/breadcrumbs.ts b/packages/browser/src/integrations/breadcrumbs.ts index 5dc7cc8fb7c7..54429bda18b4 100644 --- a/packages/browser/src/integrations/breadcrumbs.ts +++ b/packages/browser/src/integrations/breadcrumbs.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable max-lines */ import { getCurrentHub } from '@sentry/core'; -import { Event, Integration, Severity } from '@sentry/types'; +import { Event, Integration } from '@sentry/types'; import { addInstrumentationHandler, getEventDescription, @@ -9,6 +9,7 @@ import { htmlTreeAsString, parseUrl, safeJoin, + severityFromString, } from '@sentry/utils'; /** JSDoc */ @@ -171,7 +172,7 @@ function _consoleBreadcrumb(handlerData: { [key: string]: any }): void { arguments: handlerData.args, logger: 'console', }, - level: Severity.fromString(handlerData.level), + level: severityFromString(handlerData.level), message: safeJoin(handlerData.args, ' '), }; @@ -244,7 +245,7 @@ function _fetchBreadcrumb(handlerData: { [key: string]: any }): void { { category: 'fetch', data: handlerData.fetchData, - level: Severity.Error, + level: 'error', type: 'http', }, { diff --git a/packages/browser/src/integrations/globalhandlers.ts b/packages/browser/src/integrations/globalhandlers.ts index ad69493676e9..b936d263e0dd 100644 --- a/packages/browser/src/integrations/globalhandlers.ts +++ b/packages/browser/src/integrations/globalhandlers.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { getCurrentHub } from '@sentry/core'; -import { Event, EventHint, Hub, Integration, Primitive, Severity } from '@sentry/types'; +import { Event, EventHint, Hub, Integration, Primitive } from '@sentry/types'; import { addExceptionMechanism, addInstrumentationHandler, @@ -146,7 +146,7 @@ function _installGlobalOnUnhandledRejectionHandler(): void { rejection: true, }); - event.level = Severity.Error; + event.level = 'error'; addMechanismAndCapture(hub, error, event, 'onunhandledrejection'); return; diff --git a/packages/browser/src/transports/base.ts b/packages/browser/src/transports/base.ts index 1f02f3f32996..0b4fb9faa195 100644 --- a/packages/browser/src/transports/base.ts +++ b/packages/browser/src/transports/base.ts @@ -9,12 +9,12 @@ import { Outcome, Response as SentryResponse, SentryRequestType, - Status, Transport, TransportOptions, } from '@sentry/types'; import { dateTimestampInSeconds, + eventStatusFromHttpCode, getGlobalObject, logger, parseRetryAfterHeader, @@ -155,7 +155,7 @@ export abstract class BaseTransport implements Transport { resolve: (value?: SentryResponse | PromiseLike | null | undefined) => void; reject: (reason?: unknown) => void; }): void { - const status = Status.fromHttpCode(response.status); + const status = eventStatusFromHttpCode(response.status); /** * "The name is case-insensitive." * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get @@ -164,7 +164,7 @@ export abstract class BaseTransport implements Transport { if (limited) logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`); - if (status === Status.Success) { + if (status === 'success') { resolve({ status }); return; } diff --git a/packages/browser/src/transports/fetch.ts b/packages/browser/src/transports/fetch.ts index 241f2a1e8bc5..46c652bdea3e 100644 --- a/packages/browser/src/transports/fetch.ts +++ b/packages/browser/src/transports/fetch.ts @@ -1,5 +1,5 @@ import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core'; -import { Event, Outcome, Response, SentryRequest, Session, TransportOptions } from '@sentry/types'; +import { Event, Response, SentryRequest, Session, TransportOptions } from '@sentry/types'; import { SentryError, supportsReferrerPolicy, SyncPromise } from '@sentry/utils'; import { BaseTransport } from './base'; @@ -37,7 +37,7 @@ export class FetchTransport extends BaseTransport { */ private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike { if (this._isRateLimited(sentryRequest.type)) { - this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type); + this.recordLostEvent('ratelimit_backoff', sentryRequest.type); return Promise.reject({ event: originalPayload, @@ -89,9 +89,9 @@ export class FetchTransport extends BaseTransport { .then(undefined, reason => { // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError. if (reason instanceof SentryError) { - this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type); + this.recordLostEvent('queue_overflow', sentryRequest.type); } else { - this.recordLostEvent(Outcome.NetworkError, sentryRequest.type); + this.recordLostEvent('network_error', sentryRequest.type); } throw reason; }); diff --git a/packages/browser/src/transports/xhr.ts b/packages/browser/src/transports/xhr.ts index 771cb16d2a51..1d5dd91f9c0b 100644 --- a/packages/browser/src/transports/xhr.ts +++ b/packages/browser/src/transports/xhr.ts @@ -1,5 +1,5 @@ import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core'; -import { Event, Outcome, Response, SentryRequest, Session } from '@sentry/types'; +import { Event, Response, SentryRequest, Session } from '@sentry/types'; import { SentryError, SyncPromise } from '@sentry/utils'; import { BaseTransport } from './base'; @@ -26,7 +26,7 @@ export class XHRTransport extends BaseTransport { */ private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike { if (this._isRateLimited(sentryRequest.type)) { - this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type); + this.recordLostEvent('ratelimit_backoff', sentryRequest.type); return Promise.reject({ event: originalPayload, @@ -66,9 +66,9 @@ export class XHRTransport extends BaseTransport { .then(undefined, reason => { // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError. if (reason instanceof SentryError) { - this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type); + this.recordLostEvent('queue_overflow', sentryRequest.type); } else { - this.recordLostEvent(Outcome.NetworkError, sentryRequest.type); + this.recordLostEvent('network_error', sentryRequest.type); } throw reason; }); diff --git a/packages/browser/test/unit/mocks/simpletransport.ts b/packages/browser/test/unit/mocks/simpletransport.ts index 01e0d6b6b12c..0066f9c8c6cc 100644 --- a/packages/browser/test/unit/mocks/simpletransport.ts +++ b/packages/browser/test/unit/mocks/simpletransport.ts @@ -1,13 +1,13 @@ -import { SyncPromise } from '@sentry/utils'; +import { eventStatusFromHttpCode, SyncPromise } from '@sentry/utils'; -import { Event, Response, Status } from '../../../src'; +import { Event, Response } from '../../../src'; import { BaseTransport } from '../../../src/transports'; export class SimpleTransport extends BaseTransport { public sendEvent(_: Event): PromiseLike { return this._buffer.add(() => SyncPromise.resolve({ - status: Status.fromHttpCode(200), + status: eventStatusFromHttpCode(200), }), ); } diff --git a/packages/browser/test/unit/transports/base.test.ts b/packages/browser/test/unit/transports/base.test.ts index 660163527048..9180fbabc8f3 100644 --- a/packages/browser/test/unit/transports/base.test.ts +++ b/packages/browser/test/unit/transports/base.test.ts @@ -1,5 +1,3 @@ -import { Outcome } from '@sentry/types'; - import { BaseTransport } from '../../../src/transports/base'; const testDsn = 'https://123@sentry.io/42'; @@ -44,12 +42,12 @@ describe('BaseTransport', () => { it('sends beacon request when there are outcomes captured and visibility changed to `hidden`', () => { const transport = new SimpleTransport({ dsn: testDsn, sendClientReports: true }); - transport.recordLostEvent(Outcome.BeforeSend, 'event'); + transport.recordLostEvent('before_send', 'event'); visibilityState = 'hidden'; document.dispatchEvent(new Event('visibilitychange')); - const outcomes = [{ reason: Outcome.BeforeSend, category: 'error', quantity: 1 }]; + const outcomes = [{ reason: 'before_send', category: 'error', quantity: 1 }]; expect(sendBeaconSpy).toHaveBeenCalledWith( envelopeEndpoint, @@ -59,7 +57,7 @@ describe('BaseTransport', () => { it('doesnt send beacon request when there are outcomes captured, but visibility state did not change to `hidden`', () => { const transport = new SimpleTransport({ dsn: testDsn, sendClientReports: true }); - transport.recordLostEvent(Outcome.BeforeSend, 'event'); + transport.recordLostEvent('before_send', 'event'); visibilityState = 'visible'; document.dispatchEvent(new Event('visibilitychange')); @@ -70,21 +68,21 @@ describe('BaseTransport', () => { it('correctly serializes request with different categories/reasons pairs', () => { const transport = new SimpleTransport({ dsn: testDsn, sendClientReports: true }); - transport.recordLostEvent(Outcome.BeforeSend, 'event'); - transport.recordLostEvent(Outcome.BeforeSend, 'event'); - transport.recordLostEvent(Outcome.SampleRate, 'transaction'); - transport.recordLostEvent(Outcome.NetworkError, 'session'); - transport.recordLostEvent(Outcome.NetworkError, 'session'); - transport.recordLostEvent(Outcome.RateLimitBackoff, 'event'); + transport.recordLostEvent('before_send', 'event'); + transport.recordLostEvent('before_send', 'event'); + transport.recordLostEvent('sample_rate', 'transaction'); + transport.recordLostEvent('network_error', 'session'); + transport.recordLostEvent('network_error', 'session'); + transport.recordLostEvent('ratelimit_backoff', 'event'); visibilityState = 'hidden'; document.dispatchEvent(new Event('visibilitychange')); const outcomes = [ - { reason: Outcome.BeforeSend, category: 'error', quantity: 2 }, - { reason: Outcome.SampleRate, category: 'transaction', quantity: 1 }, - { reason: Outcome.NetworkError, category: 'session', quantity: 2 }, - { reason: Outcome.RateLimitBackoff, category: 'error', quantity: 1 }, + { reason: 'before_send', category: 'error', quantity: 2 }, + { reason: 'sample_rate', category: 'transaction', quantity: 1 }, + { reason: 'network_error', category: 'session', quantity: 2 }, + { reason: 'ratelimit_backoff', category: 'error', quantity: 1 }, ]; expect(sendBeaconSpy).toHaveBeenCalledWith( @@ -97,12 +95,12 @@ describe('BaseTransport', () => { const tunnel = 'https://hello.com/world'; const transport = new SimpleTransport({ dsn: testDsn, sendClientReports: true, tunnel }); - transport.recordLostEvent(Outcome.BeforeSend, 'event'); + transport.recordLostEvent('before_send', 'event'); visibilityState = 'hidden'; document.dispatchEvent(new Event('visibilitychange')); - const outcomes = [{ reason: Outcome.BeforeSend, category: 'error', quantity: 1 }]; + const outcomes = [{ reason: 'before_send', category: 'error', quantity: 1 }]; expect(sendBeaconSpy).toHaveBeenCalledWith( tunnel, diff --git a/packages/browser/test/unit/transports/fetch.test.ts b/packages/browser/test/unit/transports/fetch.test.ts index a6f39cfc8c97..afb427b4026e 100644 --- a/packages/browser/test/unit/transports/fetch.test.ts +++ b/packages/browser/test/unit/transports/fetch.test.ts @@ -1,7 +1,6 @@ -import { Outcome } from '@sentry/types'; import { SentryError } from '@sentry/utils'; -import { Event, Response, Status, Transports } from '../../../src'; +import { Event, Response, Transports } from '../../../src'; const testDsn = 'https://123@sentry.io/42'; const storeUrl = 'https://sentry.io/api/42/store/?sentry_key=123&sentry_version=7'; @@ -61,7 +60,7 @@ describe('FetchTransport', () => { const res = await transport.sendEvent(eventPayload); - expect((res as Response).status).toBe(Status.Success); + expect((res as Response).status).toBe('success'); expect(fetch).toHaveBeenCalledWith(storeUrl, { body: JSON.stringify(eventPayload), method: 'POST', @@ -117,7 +116,7 @@ describe('FetchTransport', () => { try { await transport.sendEvent(eventPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.NetworkError, 'event'); + expect(spy).toHaveBeenCalledWith('network_error', 'event'); } }); @@ -129,7 +128,7 @@ describe('FetchTransport', () => { try { await transport.sendEvent(transactionPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.QueueOverflow, 'transaction'); + expect(spy).toHaveBeenCalledWith('queue_overflow', 'transaction'); } }); @@ -149,7 +148,7 @@ describe('FetchTransport', () => { const res = await transport.sendEvent(eventPayload); - expect((res as Response).status).toBe(Status.Success); + expect((res as Response).status).toBe('success'); expect(fetch).toHaveBeenCalledWith(storeUrl, { body: JSON.stringify(eventPayload), headers: { @@ -176,7 +175,7 @@ describe('FetchTransport', () => { const res = await transport.sendEvent(eventPayload); - expect((res as Response).status).toBe(Status.Success); + expect((res as Response).status).toBe('success'); expect(fetch).toHaveBeenCalledWith(storeUrl, { body: JSON.stringify(eventPayload), credentials: 'include', @@ -232,7 +231,7 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers: new Headers() })); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(2); }); @@ -275,7 +274,7 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers: new Headers() })); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(2); try { @@ -290,7 +289,7 @@ describe('FetchTransport', () => { } const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(3); }); @@ -357,11 +356,11 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers: new Headers() })); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(2); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(3); }); @@ -428,11 +427,11 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers: new Headers() })); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(2); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(3); }); @@ -460,7 +459,7 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers })); let eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalled(); try { @@ -477,7 +476,7 @@ describe('FetchTransport', () => { window.fetch.mockImplementation(() => Promise.resolve({ status: 200, headers: new Headers() })); eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(fetch).toHaveBeenCalledTimes(2); }); @@ -490,13 +489,13 @@ describe('FetchTransport', () => { try { await transport.sendEvent(eventPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.RateLimitBackoff, 'event'); + expect(spy).toHaveBeenCalledWith('ratelimit_backoff', 'event'); } try { await transport.sendEvent(transactionPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.RateLimitBackoff, 'transaction'); + expect(spy).toHaveBeenCalledWith('ratelimit_backoff', 'transaction'); } }); }); diff --git a/packages/browser/test/unit/transports/xhr.test.ts b/packages/browser/test/unit/transports/xhr.test.ts index 9d4291edd092..fcf7c26211da 100644 --- a/packages/browser/test/unit/transports/xhr.test.ts +++ b/packages/browser/test/unit/transports/xhr.test.ts @@ -1,8 +1,7 @@ -import { Outcome } from '@sentry/types'; import { SentryError } from '@sentry/utils'; import { fakeServer, SinonFakeServer } from 'sinon'; -import { Event, Response, Status, Transports } from '../../../src'; +import { Event, Response, Transports } from '../../../src'; const testDsn = 'https://123@sentry.io/42'; const storeUrl = 'https://sentry.io/api/42/store/?sentry_key=123&sentry_version=7'; @@ -41,7 +40,7 @@ describe('XHRTransport', () => { const res = await transport.sendEvent(eventPayload); - expect((res as Response).status).toBe(Status.Success); + expect((res as Response).status).toBe('success'); const request = server.requests[0]; expect(server.requests.length).toBe(1); expect(request.method).toBe('POST'); @@ -79,7 +78,7 @@ describe('XHRTransport', () => { try { await transport.sendEvent(eventPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.NetworkError, 'event'); + expect(spy).toHaveBeenCalledWith('network_error', 'event'); } }); @@ -91,7 +90,7 @@ describe('XHRTransport', () => { try { await transport.sendEvent(transactionPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.QueueOverflow, 'transaction'); + expect(spy).toHaveBeenCalledWith('queue_overflow', 'transaction'); } }); @@ -107,7 +106,7 @@ describe('XHRTransport', () => { const res = await transport.sendEvent(eventPayload); const request = server.requests[0]; - expect((res as Response).status).toBe(Status.Success); + expect((res as Response).status).toBe('success'); const requestHeaders: { [key: string]: string } = request.requestHeaders as { [key: string]: string }; expect(requestHeaders['Accept']).toBe('application/json'); }); @@ -157,7 +156,7 @@ describe('XHRTransport', () => { server.respondWith('POST', storeUrl, [200, {}, '']); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(2); }); @@ -197,7 +196,7 @@ describe('XHRTransport', () => { } const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(server.requests.length).toBe(2); try { @@ -214,7 +213,7 @@ describe('XHRTransport', () => { server.respondWith('POST', storeUrl, [200, {}, '']); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(3); }); @@ -285,11 +284,11 @@ describe('XHRTransport', () => { server.respondWith('POST', envelopeUrl, [200, {}, '']); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(2); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(server.requests.length).toBe(3); }); @@ -356,11 +355,11 @@ describe('XHRTransport', () => { server.respondWith('POST', envelopeUrl, [200, {}, '']); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(2); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toBe(Status.Success); + expect(transactionRes.status).toBe('success'); expect(server.requests.length).toBe(3); }); @@ -386,7 +385,7 @@ describe('XHRTransport', () => { .mockImplementationOnce(() => afterLimit); let eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(1); try { @@ -403,7 +402,7 @@ describe('XHRTransport', () => { server.respondWith('POST', storeUrl, [200, {}, '']); eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toBe(Status.Success); + expect(eventRes.status).toBe('success'); expect(server.requests.length).toBe(2); }); @@ -416,13 +415,13 @@ describe('XHRTransport', () => { try { await transport.sendEvent(eventPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.RateLimitBackoff, 'event'); + expect(spy).toHaveBeenCalledWith('ratelimit_backoff', 'event'); } try { await transport.sendEvent(transactionPayload); } catch (_) { - expect(spy).toHaveBeenCalledWith(Outcome.RateLimitBackoff, 'transaction'); + expect(spy).toHaveBeenCalledWith('ratelimit_backoff', 'transaction'); } }); }); diff --git a/packages/core/src/basebackend.ts b/packages/core/src/basebackend.ts index eb7e598a02ad..ffdcd22af6c0 100644 --- a/packages/core/src/basebackend.ts +++ b/packages/core/src/basebackend.ts @@ -1,4 +1,4 @@ -import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types'; +import { Event, EventHint, Options, Session, SeverityLevel, Transport } from '@sentry/types'; import { logger, SentryError } from '@sentry/utils'; import { NoopTransport } from './transports/noop'; @@ -29,7 +29,7 @@ export interface Backend { eventFromException(exception: any, hint?: EventHint): PromiseLike; /** Creates a {@link Event} from a plain message. */ - eventFromMessage(message: string, level?: Severity, hint?: EventHint): PromiseLike; + eventFromMessage(message: string, level?: SeverityLevel, hint?: EventHint): PromiseLike; /** Submits the event to Sentry */ sendEvent(event: Event): void; @@ -83,7 +83,7 @@ export abstract class BaseBackend implements Backend { /** * @inheritDoc */ - public eventFromMessage(_message: string, _level?: Severity, _hint?: EventHint): PromiseLike { + public eventFromMessage(_message: string, _level?: SeverityLevel, _hint?: EventHint): PromiseLike { throw new SentryError('Backend has to implement `eventFromMessage` method'); } diff --git a/packages/core/src/baseclient.ts b/packages/core/src/baseclient.ts index 3a9a50b8de33..e9c4f1ca48bf 100644 --- a/packages/core/src/baseclient.ts +++ b/packages/core/src/baseclient.ts @@ -7,9 +7,7 @@ import { Integration, IntegrationClass, Options, - Outcome, - SessionStatus, - Severity, + SeverityLevel, Transport, } from '@sentry/types'; import { @@ -127,7 +125,7 @@ export abstract class BaseClient implement /** * @inheritDoc */ - public captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined { + public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string | undefined { let eventId: string | undefined = hint && hint.event_id; const promisedEvent = isPrimitive(message) @@ -268,12 +266,12 @@ export abstract class BaseClient implement // A session is updated and that session update is sent in only one of the two following scenarios: // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - const sessionNonTerminal = session.status === SessionStatus.Ok; + const sessionNonTerminal = session.status === 'ok'; const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); if (shouldUpdateAndSend) { session.update({ - ...(crashed && { status: SessionStatus.Crashed }), + ...(crashed && { status: 'crashed' }), errors: session.errors || Number(errored || crashed), }); this.captureSession(session); @@ -541,7 +539,7 @@ export abstract class BaseClient implement // 0.0 === 0% events are sent // Sampling for transaction happens somewhere else if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - recordLostEvent(Outcome.SampleRate, 'event'); + recordLostEvent('sample_rate', 'event'); return SyncPromise.reject( new SentryError( `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, @@ -552,7 +550,7 @@ export abstract class BaseClient implement return this._prepareEvent(event, scope, hint) .then(prepared => { if (prepared === null) { - recordLostEvent(Outcome.EventProcessor, event.type || 'event'); + recordLostEvent('event_processor', event.type || 'event'); throw new SentryError('An event processor returned null, will not send event.'); } @@ -566,7 +564,7 @@ export abstract class BaseClient implement }) .then(processedEvent => { if (processedEvent === null) { - recordLostEvent(Outcome.BeforeSend, event.type || 'event'); + recordLostEvent('before_send', event.type || 'event'); throw new SentryError('`beforeSend` returned `null`, will not send event.'); } diff --git a/packages/core/src/transports/noop.ts b/packages/core/src/transports/noop.ts index ae026892271e..bf1a1603b53a 100644 --- a/packages/core/src/transports/noop.ts +++ b/packages/core/src/transports/noop.ts @@ -1,4 +1,4 @@ -import { Event, Response, Status, Transport } from '@sentry/types'; +import { Event, Response, Transport } from '@sentry/types'; import { SyncPromise } from '@sentry/utils'; /** Noop transport */ @@ -9,7 +9,7 @@ export class NoopTransport implements Transport { public sendEvent(_: Event): PromiseLike { return SyncPromise.resolve({ reason: `NoopTransport: Event has been skipped because no Dsn is configured.`, - status: Status.Skipped, + status: 'skipped', }); } diff --git a/packages/core/test/lib/base.test.ts b/packages/core/test/lib/base.test.ts index f29607e5ac94..cd8d7f992fb4 100644 --- a/packages/core/test/lib/base.test.ts +++ b/packages/core/test/lib/base.test.ts @@ -1,5 +1,5 @@ import { Hub, Scope, Session } from '@sentry/hub'; -import { Event, Outcome, Severity, Span, Transport } from '@sentry/types'; +import { Event, Span, Transport } from '@sentry/types'; import { logger, SentryError, SyncPromise } from '@sentry/utils'; import * as integrationModule from '../../src/integration'; @@ -313,7 +313,7 @@ describe('BaseClient', () => { scope.setExtra('foo', 'wat'); client.captureMessage( 'test message', - Severity.Warning, + 'warning', { captureContext: { extra: { @@ -882,7 +882,7 @@ describe('BaseClient', () => { client.captureEvent({ message: 'hello' }, {}); - expect(recordLostEventSpy).toHaveBeenCalledWith(Outcome.BeforeSend, 'event'); + expect(recordLostEventSpy).toHaveBeenCalledWith('before_send', 'event'); }); test('eventProcessor can drop the even when it returns null', () => { @@ -914,7 +914,7 @@ describe('BaseClient', () => { scope.addEventProcessor(() => null); client.captureEvent({ message: 'hello' }, {}, scope); - expect(recordLostEventSpy).toHaveBeenCalledWith(Outcome.EventProcessor, 'event'); + expect(recordLostEventSpy).toHaveBeenCalledWith('event_processor', 'event'); }); test('eventProcessor sends an event and logs when it crashes', () => { @@ -958,7 +958,7 @@ describe('BaseClient', () => { ); client.captureEvent({ message: 'hello' }, {}); - expect(recordLostEventSpy).toHaveBeenCalledWith(Outcome.SampleRate, 'event'); + expect(recordLostEventSpy).toHaveBeenCalledWith('sample_rate', 'event'); }); }); diff --git a/packages/core/test/lib/request.test.ts b/packages/core/test/lib/request.test.ts index 6e27bb26a4af..bd9c3e424bac 100644 --- a/packages/core/test/lib/request.test.ts +++ b/packages/core/test/lib/request.test.ts @@ -1,4 +1,4 @@ -import { DebugMeta, Event, SentryRequest, TransactionSamplingMethod } from '@sentry/types'; +import { DebugMeta, Event, SentryRequest } from '@sentry/types'; import { initAPIDetails } from '../../src/api'; import { eventToSentryRequest, sessionToSentryRequest } from '../../src/request'; @@ -44,21 +44,21 @@ describe('eventToSentryRequest', () => { }); it('adds transaction sampling information to item header', () => { - event.debug_meta = { transactionSampling: { method: TransactionSamplingMethod.Rate, rate: 0.1121 } }; + event.debug_meta = { transactionSampling: { method: 'client_rate', rate: 0.1121 } }; const result = eventToSentryRequest(event, api); const envelope = parseEnvelopeRequest(result); expect(envelope.itemHeader).toEqual( expect.objectContaining({ - sample_rates: [{ id: TransactionSamplingMethod.Rate, rate: 0.1121 }], + sample_rates: [{ id: 'client_rate', rate: 0.1121 }], }), ); }); it('removes transaction sampling information (and only that) from debug_meta', () => { event.debug_meta = { - transactionSampling: { method: TransactionSamplingMethod.Sampler, rate: 0.1121 }, + transactionSampling: { method: 'client_sampler', rate: 0.1121 }, dog: 'Charlie', } as DebugMeta; @@ -71,7 +71,7 @@ describe('eventToSentryRequest', () => { it('removes debug_meta entirely if it ends up empty', () => { event.debug_meta = { - transactionSampling: { method: TransactionSamplingMethod.Rate, rate: 0.1121 }, + transactionSampling: { method: 'client_rate', rate: 0.1121 }, } as DebugMeta; const result = eventToSentryRequest(event, api); diff --git a/packages/core/test/mocks/backend.ts b/packages/core/test/mocks/backend.ts index 7d21f4bfa323..f98e5adf4f69 100644 --- a/packages/core/test/mocks/backend.ts +++ b/packages/core/test/mocks/backend.ts @@ -1,5 +1,5 @@ import { Session } from '@sentry/hub'; -import { Event, Options, Severity, Transport } from '@sentry/types'; +import { Event, Options, SeverityLevel, Transport } from '@sentry/types'; import { SyncPromise } from '@sentry/utils'; import { BaseBackend } from '../../src/basebackend'; @@ -38,7 +38,7 @@ export class TestBackend extends BaseBackend { }); } - public eventFromMessage(message: string, level: Severity = Severity.Info): PromiseLike { + public eventFromMessage(message: string, level: SeverityLevel = 'info'): PromiseLike { return SyncPromise.resolve({ message, level }); } diff --git a/packages/core/test/mocks/transport.ts b/packages/core/test/mocks/transport.ts index 7b23c895d9da..29c3be68d226 100644 --- a/packages/core/test/mocks/transport.ts +++ b/packages/core/test/mocks/transport.ts @@ -1,4 +1,4 @@ -import { Event, Response, Status, Transport } from '@sentry/types'; +import { Event, Response, Transport } from '@sentry/types'; import { PromiseBuffer, SyncPromise } from '@sentry/utils'; async function sleep(delay: number): Promise { @@ -20,7 +20,7 @@ export class FakeTransport implements Transport { new SyncPromise(async res => { await sleep(this.delay); this.sentCount += 1; - res({ status: Status.Success }); + res({ status: 'success' }); }), ); } diff --git a/packages/hub/src/hub.ts b/packages/hub/src/hub.ts index 0ff7ef13ec7b..c7fd4cac85e4 100644 --- a/packages/hub/src/hub.ts +++ b/packages/hub/src/hub.ts @@ -13,8 +13,7 @@ import { IntegrationClass, Primitive, SessionContext, - SessionStatus, - Severity, + SeverityLevel, Span, SpanContext, Transaction, @@ -216,7 +215,7 @@ export class Hub implements HubInterface { /** * @inheritDoc */ - public captureMessage(message: string, level?: Severity, hint?: EventHint): string { + public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string { const eventId = (this._lastEventId = uuid4()); let finalHint = hint; @@ -451,8 +450,8 @@ export class Hub implements HubInterface { if (scope) { // End existing session if there's one const currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === SessionStatus.Ok) { - currentSession.update({ status: SessionStatus.Exited }); + if (currentSession && currentSession.status === 'ok') { + currentSession.update({ status: 'exited' }); } this.endSession(); diff --git a/packages/hub/src/scope.ts b/packages/hub/src/scope.ts index 21c17f4a214b..940d0443c9f7 100644 --- a/packages/hub/src/scope.ts +++ b/packages/hub/src/scope.ts @@ -13,7 +13,7 @@ import { RequestSession, Scope as ScopeInterface, ScopeContext, - Severity, + SeverityLevel, Span, Transaction, User, @@ -61,7 +61,7 @@ export class Scope implements ScopeInterface { protected _fingerprint?: string[]; /** Severity */ - protected _level?: Severity; + protected _level?: SeverityLevel; /** Transaction Name */ protected _transactionName?: string; @@ -202,7 +202,7 @@ export class Scope implements ScopeInterface { /** * @inheritDoc */ - public setLevel(level: Severity): this { + public setLevel(level: SeverityLevel): this { this._level = level; this._notifyScopeListeners(); return this; diff --git a/packages/hub/src/session.ts b/packages/hub/src/session.ts index 1bca2377cdd5..3206ef9306dc 100644 --- a/packages/hub/src/session.ts +++ b/packages/hub/src/session.ts @@ -13,7 +13,7 @@ export class Session implements SessionInterface { public timestamp: number; public started: number; public duration?: number = 0; - public status: SessionStatus = SessionStatus.Ok; + public status: SessionStatus = 'ok'; public environment?: string; public ipAddress?: string; public init: boolean = true; @@ -88,11 +88,11 @@ export class Session implements SessionInterface { } /** JSDoc */ - public close(status?: Exclude): void { + public close(status?: Exclude): void { if (status) { this.update({ status }); - } else if (this.status === SessionStatus.Ok) { - this.update({ status: SessionStatus.Exited }); + } else if (this.status === 'ok') { + this.update({ status: 'exited' }); } else { this.update(); } diff --git a/packages/hub/src/sessionflusher.ts b/packages/hub/src/sessionflusher.ts index bb898030efb4..82aa0af8c4c2 100644 --- a/packages/hub/src/sessionflusher.ts +++ b/packages/hub/src/sessionflusher.ts @@ -113,13 +113,13 @@ export class SessionFlusher implements SessionFlusherLike { } switch (status) { - case RequestSessionStatus.Errored: + case 'errored': aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; return aggregationCounts.errored; - case RequestSessionStatus.Ok: + case 'ok': aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; return aggregationCounts.exited; - case RequestSessionStatus.Crashed: + default: aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; return aggregationCounts.crashed; } diff --git a/packages/hub/test/scope.test.ts b/packages/hub/test/scope.test.ts index 027f29e14d3c..9b1760dcd11c 100644 --- a/packages/hub/test/scope.test.ts +++ b/packages/hub/test/scope.test.ts @@ -1,4 +1,4 @@ -import { Event, EventHint, RequestSessionStatus, Severity } from '@sentry/types'; +import { Event, EventHint } from '@sentry/types'; import { getGlobalObject } from '@sentry/utils'; import { addGlobalEventProcessor, Scope } from '../src'; @@ -85,8 +85,8 @@ describe('Scope', () => { test('setLevel', () => { const scope = new Scope(); - scope.setLevel(Severity.Critical); - expect((scope as any)._level).toEqual(Severity.Critical); + scope.setLevel('critical'); + expect((scope as any)._level).toEqual('critical'); }); test('setTransactionName', () => { @@ -131,8 +131,8 @@ describe('Scope', () => { test('chaining', () => { const scope = new Scope(); - scope.setLevel(Severity.Critical).setUser({ id: '1' }); - expect((scope as any)._level).toEqual(Severity.Critical); + scope.setLevel('critical').setUser({ id: '1' }); + expect((scope as any)._level).toEqual('critical'); expect((scope as any)._user).toEqual({ id: '1' }); }); }); @@ -147,7 +147,7 @@ describe('Scope', () => { test('_requestSession clone', () => { const parentScope = new Scope(); - parentScope.setRequestSession({ status: RequestSessionStatus.Errored }); + parentScope.setRequestSession({ status: 'errored' }); const scope = Scope.clone(parentScope); expect(parentScope.getRequestSession()).toEqual(scope.getRequestSession()); }); @@ -174,16 +174,16 @@ describe('Scope', () => { // Test that ensures if the status value of `status` of `_requestSession` is changed in a child scope // that it should also change in parent scope because we are copying the reference to the object const parentScope = new Scope(); - parentScope.setRequestSession({ status: RequestSessionStatus.Errored }); + parentScope.setRequestSession({ status: 'errored' }); const scope = Scope.clone(parentScope); const requestSession = scope.getRequestSession(); if (requestSession) { - requestSession.status = RequestSessionStatus.Ok; + requestSession.status = 'ok'; } - expect(parentScope.getRequestSession()).toEqual({ status: RequestSessionStatus.Ok }); - expect(scope.getRequestSession()).toEqual({ status: RequestSessionStatus.Ok }); + expect(parentScope.getRequestSession()).toEqual({ status: 'ok' }); + expect(scope.getRequestSession()).toEqual({ status: 'ok' }); }); }); @@ -195,7 +195,7 @@ describe('Scope', () => { scope.setTag('a', 'b'); scope.setUser({ id: '1' }); scope.setFingerprint(['abcd']); - scope.setLevel(Severity.Warning); + scope.setLevel('warning'); scope.setTransactionName('/abc'); scope.addBreadcrumb({ message: 'test' }); scope.setContext('os', { id: '1' }); @@ -284,9 +284,9 @@ describe('Scope', () => { test('scope level should have priority over event level', () => { expect.assertions(1); const scope = new Scope(); - scope.setLevel(Severity.Warning); + scope.setLevel('warning'); const event: Event = {}; - event.level = Severity.Critical; + event.level = 'critical'; return scope.applyToEvent(event).then(processedEvent => { expect(processedEvent!.level).toEqual('warning'); }); @@ -375,7 +375,7 @@ describe('Scope', () => { scope.setUser({ id: '1' }); scope.setFingerprint(['abcd']); scope.addBreadcrumb({ message: 'test' }); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); expect((scope as any)._extra).toEqual({ a: 2 }); scope.clear(); expect((scope as any)._extra).toEqual({}); @@ -400,9 +400,9 @@ describe('Scope', () => { scope.setContext('foo', { id: '1' }); scope.setContext('bar', { id: '2' }); scope.setUser({ id: '1337' }); - scope.setLevel(Severity.Info); + scope.setLevel('info'); scope.setFingerprint(['foo']); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); }); test('given no data, returns the original scope', () => { @@ -448,9 +448,9 @@ describe('Scope', () => { localScope.setContext('bar', { id: '3' }); localScope.setContext('baz', { id: '4' }); localScope.setUser({ id: '42' }); - localScope.setLevel(Severity.Warning); + localScope.setLevel('warning'); localScope.setFingerprint(['bar']); - (localScope as any)._requestSession = { status: RequestSessionStatus.Ok }; + (localScope as any)._requestSession = { status: 'ok' }; const updatedScope = scope.update(localScope) as any; @@ -470,9 +470,9 @@ describe('Scope', () => { foo: { id: '1' }, }); expect(updatedScope._user).toEqual({ id: '42' }); - expect(updatedScope._level).toEqual(Severity.Warning); + expect(updatedScope._level).toEqual('warning'); expect(updatedScope._fingerprint).toEqual(['bar']); - expect(updatedScope._requestSession.status).toEqual(RequestSessionStatus.Ok); + expect(updatedScope._requestSession.status).toEqual('ok'); }); test('given an empty instance of Scope, it should preserve all the original scope data', () => { @@ -491,9 +491,9 @@ describe('Scope', () => { foo: { id: '1' }, }); expect(updatedScope._user).toEqual({ id: '1337' }); - expect(updatedScope._level).toEqual(Severity.Info); + expect(updatedScope._level).toEqual('info'); expect(updatedScope._fingerprint).toEqual(['foo']); - expect(updatedScope._requestSession.status).toEqual(RequestSessionStatus.Ok); + expect(updatedScope._requestSession.status).toEqual('ok'); }); test('given a plain object, it should merge two together, with the passed object having priority', () => { @@ -501,10 +501,10 @@ describe('Scope', () => { contexts: { bar: { id: '3' }, baz: { id: '4' } }, extra: { bar: '3', baz: '4' }, fingerprint: ['bar'], - level: Severity.Warning, + level: 'warning', tags: { bar: '3', baz: '4' }, user: { id: '42' }, - requestSession: { status: RequestSessionStatus.Errored }, + requestSession: { status: 'errored' }, }; const updatedScope = scope.update(localAttributes) as any; @@ -524,9 +524,9 @@ describe('Scope', () => { foo: { id: '1' }, }); expect(updatedScope._user).toEqual({ id: '42' }); - expect(updatedScope._level).toEqual(Severity.Warning); + expect(updatedScope._level).toEqual('warning'); expect(updatedScope._fingerprint).toEqual(['bar']); - expect(updatedScope._requestSession).toEqual({ status: RequestSessionStatus.Errored }); + expect(updatedScope._requestSession).toEqual({ status: 'errored' }); }); }); diff --git a/packages/hub/test/session.test.ts b/packages/hub/test/session.test.ts index d334becd4821..f25e5ad4189b 100644 --- a/packages/hub/test/session.test.ts +++ b/packages/hub/test/session.test.ts @@ -1,4 +1,4 @@ -import { SessionContext, SessionStatus } from '@sentry/types'; +import { SessionContext } from '@sentry/types'; import { timestampInSeconds } from '@sentry/utils'; import { Session } from '../src/session'; @@ -16,7 +16,7 @@ describe('Session', () => { init: true, sid: expect.any(String), started: expect.stringMatching(currentYear), - status: SessionStatus.Ok, + status: 'ok', timestamp: expect.stringMatching(currentYear), }); @@ -74,7 +74,7 @@ describe('Session', () => { ], ['sets an userAgent', { userAgent: 'Mozilla/5.0' }, { attrs: { user_agent: 'Mozilla/5.0' } }], ['sets errors', { errors: 3 }, { errors: 3 }], - ['sets status', { status: SessionStatus.Crashed }, { status: SessionStatus.Crashed }], + ['sets status', { status: 'crashed' }, { status: 'crashed' }], ]; test.each(table)('%s', (...test) => { @@ -93,26 +93,26 @@ describe('Session', () => { describe('close', () => { it('exits a normal session', () => { const session = new Session(); - expect(session.status).toEqual(SessionStatus.Ok); + expect(session.status).toEqual('ok'); session.close(); - expect(session.status).toEqual(SessionStatus.Exited); + expect(session.status).toEqual('exited'); }); it('updates session status when give status', () => { const session = new Session(); - expect(session.status).toEqual(SessionStatus.Ok); + expect(session.status).toEqual('ok'); - session.close(SessionStatus.Abnormal); - expect(session.status).toEqual(SessionStatus.Abnormal); + session.close('abnormal'); + expect(session.status).toEqual('abnormal'); }); it('only changes status ok to exited', () => { const session = new Session(); - session.update({ status: SessionStatus.Crashed }); - expect(session.status).toEqual(SessionStatus.Crashed); + session.update({ status: 'crashed' }); + expect(session.status).toEqual('crashed'); session.close(); - expect(session.status).toEqual(SessionStatus.Crashed); + expect(session.status).toEqual('crashed'); }); }); }); diff --git a/packages/hub/test/sessionflusher.test.ts b/packages/hub/test/sessionflusher.test.ts index 1250f20bfc5f..3c7dc9782615 100644 --- a/packages/hub/test/sessionflusher.test.ts +++ b/packages/hub/test/sessionflusher.test.ts @@ -1,5 +1,3 @@ -import { RequestSessionStatus, Status } from '@sentry/types'; - import { SessionFlusher } from '../src/sessionflusher'; describe('Session Flusher', () => { @@ -12,7 +10,7 @@ describe('Session Flusher', () => { beforeEach(() => { jest.useFakeTimers(); - sendSession = jest.fn(() => Promise.resolve({ status: Status.Success })); + sendSession = jest.fn(() => Promise.resolve({ status: 'success' })); transport = { sendEvent: jest.fn(), sendSession, @@ -28,16 +26,16 @@ describe('Session Flusher', () => { const flusher = new SessionFlusher(transport, { release: '1.0.0', environment: 'dev' }); const date = new Date('2021-04-08T12:18:23.043Z'); - let count = (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); + let count = (flusher as any)._incrementSessionStatusCount('ok', date); expect(count).toEqual(1); - count = (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); + count = (flusher as any)._incrementSessionStatusCount('ok', date); expect(count).toEqual(2); - count = (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Errored, date); + count = (flusher as any)._incrementSessionStatusCount('errored', date); expect(count).toEqual(1); date.setMinutes(date.getMinutes() + 1); - count = (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); + count = (flusher as any)._incrementSessionStatusCount('ok', date); expect(count).toEqual(1); - count = (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Errored, date); + count = (flusher as any)._incrementSessionStatusCount('errored', date); expect(count).toEqual(1); expect(flusher.getSessionAggregates().aggregates).toEqual([ @@ -51,8 +49,8 @@ describe('Session Flusher', () => { const flusher = new SessionFlusher(transport, { release: '1.0.0' }); const date = new Date('2021-04-08T12:18:23.043Z'); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Errored, date); + (flusher as any)._incrementSessionStatusCount('ok', date); + (flusher as any)._incrementSessionStatusCount('errored', date); expect(flusher.getSessionAggregates()).toEqual({ aggregates: [{ errored: 1, exited: 1, started: '2021-04-08T12:18:00.000Z' }], @@ -77,8 +75,8 @@ describe('Session Flusher', () => { const flusher = new SessionFlusher(transport, { release: '1.0.0', environment: 'dev' }); const flusherFlushFunc = jest.spyOn(flusher, 'flush'); const date = new Date('2021-04-08T12:18:23.043Z'); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); + (flusher as any)._incrementSessionStatusCount('ok', date); + (flusher as any)._incrementSessionStatusCount('ok', date); expect(sendSession).toHaveBeenCalledTimes(0); @@ -113,8 +111,8 @@ describe('Session Flusher', () => { const flusher = new SessionFlusher(transport, { release: '1.0.x' }); const flusherFlushFunc = jest.spyOn(flusher, 'flush'); const date = new Date('2021-04-08T12:18:23.043Z'); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); - (flusher as any)._incrementSessionStatusCount(RequestSessionStatus.Ok, date); + (flusher as any)._incrementSessionStatusCount('ok', date); + (flusher as any)._incrementSessionStatusCount('ok', date); flusher.close(); expect(flusherFlushFunc).toHaveBeenCalledTimes(1); diff --git a/packages/integrations/src/captureconsole.ts b/packages/integrations/src/captureconsole.ts index 79b7c2431f51..bd3a7c055083 100644 --- a/packages/integrations/src/captureconsole.ts +++ b/packages/integrations/src/captureconsole.ts @@ -1,5 +1,5 @@ -import { EventProcessor, Hub, Integration, Severity } from '@sentry/types'; -import { fill, getGlobalObject, safeJoin } from '@sentry/utils'; +import { EventProcessor, Hub, Integration } from '@sentry/types'; +import { fill, getGlobalObject, safeJoin, severityFromString } from '@sentry/utils'; const global = getGlobalObject(); @@ -48,7 +48,7 @@ export class CaptureConsole implements Integration { if (hub.getIntegration(CaptureConsole)) { hub.withScope(scope => { - scope.setLevel(Severity.fromString(level)); + scope.setLevel(severityFromString(level)); scope.setExtra('arguments', args); scope.addEventProcessor(event => { event.logger = 'console'; diff --git a/packages/minimal/src/index.ts b/packages/minimal/src/index.ts index 117c8a769b92..15fcf7e3eaab 100644 --- a/packages/minimal/src/index.ts +++ b/packages/minimal/src/index.ts @@ -7,7 +7,7 @@ import { Extra, Extras, Primitive, - Severity, + SeverityLevel, Transaction, TransactionContext, User, @@ -53,10 +53,10 @@ export function captureException(exception: any, captureContext?: CaptureContext * Captures a message event and sends it to Sentry. * * @param message The message to send to Sentry. - * @param level Define the level of the message. + * @param SeverityLevel Define the level of the message. * @returns The generated eventId. */ -export function captureMessage(message: string, captureContext?: CaptureContext | Severity): string { +export function captureMessage(message: string, captureContext?: CaptureContext | SeverityLevel): string { let syntheticException: Error; try { throw new Error(message); diff --git a/packages/minimal/test/lib/minimal.test.ts b/packages/minimal/test/lib/minimal.test.ts index 9e25bb0a46df..48a117cd5c5d 100644 --- a/packages/minimal/test/lib/minimal.test.ts +++ b/packages/minimal/test/lib/minimal.test.ts @@ -1,5 +1,4 @@ import { getCurrentHub, getHubFromCarrier, Scope } from '@sentry/hub'; -import { Severity } from '@sentry/types'; import { _callOnClient, @@ -96,10 +95,10 @@ describe('Minimal', () => { getCurrentHub().withScope(() => { getCurrentHub().bindClient(client); const message = 'yo'; - const level = Severity.Warning; + const level = 'warning'; captureMessage(message, level); expect(client.captureMessage.mock.calls[0][0]).toBe(message); - expect(client.captureMessage.mock.calls[0][1]).toBe(Severity.Warning); + expect(client.captureMessage.mock.calls[0][1]).toBe('warning'); }); }); @@ -165,8 +164,8 @@ describe('Minimal', () => { const client: any = new TestClient({}); const scope = getCurrentHub().pushScope(); getCurrentHub().bindClient(client); - scope.setLevel(Severity.Warning); - expect(global.__SENTRY__.hub._stack[1].scope._level).toEqual(Severity.Warning); + scope.setLevel('warning'); + expect(global.__SENTRY__.hub._stack[1].scope._level).toEqual('warning'); }); }); @@ -245,16 +244,16 @@ describe('Minimal', () => { test('withScope', () => { withScope(scope => { - scope.setLevel(Severity.Warning); + scope.setLevel('warning'); scope.setFingerprint(['1']); withScope(scope2 => { - scope2.setLevel(Severity.Info); + scope2.setLevel('info'); scope2.setFingerprint(['2']); withScope(scope3 => { scope3.clear(); - expect(global.__SENTRY__.hub._stack[1].scope._level).toEqual(Severity.Warning); + expect(global.__SENTRY__.hub._stack[1].scope._level).toEqual('warning'); expect(global.__SENTRY__.hub._stack[1].scope._fingerprint).toEqual(['1']); - expect(global.__SENTRY__.hub._stack[2].scope._level).toEqual(Severity.Info); + expect(global.__SENTRY__.hub._stack[2].scope._level).toEqual('info'); expect(global.__SENTRY__.hub._stack[2].scope._fingerprint).toEqual(['2']); expect(global.__SENTRY__.hub._stack[3].scope._level).toBeUndefined(); }); diff --git a/packages/node/src/backend.ts b/packages/node/src/backend.ts index 8220d690ceb4..290dfa664dce 100644 --- a/packages/node/src/backend.ts +++ b/packages/node/src/backend.ts @@ -1,5 +1,5 @@ import { BaseBackend, getCurrentHub } from '@sentry/core'; -import { Event, EventHint, Mechanism, Severity, Transport, TransportOptions } from '@sentry/types'; +import { Event, EventHint, Mechanism, SeverityLevel, Transport, TransportOptions } from '@sentry/types'; import { addExceptionMechanism, addExceptionTypeValue, @@ -73,7 +73,7 @@ export class NodeBackend extends BaseBackend { /** * @inheritDoc */ - public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike { + public eventFromMessage(message: string, level: SeverityLevel = 'info', hint?: EventHint): PromiseLike { const event: Event = { event_id: hint && hint.event_id, level, diff --git a/packages/node/src/client.ts b/packages/node/src/client.ts index 7f4842b48ad4..c5f19ed611d0 100644 --- a/packages/node/src/client.ts +++ b/packages/node/src/client.ts @@ -1,6 +1,6 @@ import { BaseClient, Scope, SDK_VERSION } from '@sentry/core'; import { SessionFlusher } from '@sentry/hub'; -import { Event, EventHint, RequestSessionStatus } from '@sentry/types'; +import { Event, EventHint } from '@sentry/types'; import { logger } from '@sentry/utils'; import { NodeBackend } from './backend'; @@ -48,8 +48,8 @@ export class NodeClient extends BaseClient { // Necessary checks to ensure this is code block is executed only within a request // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === RequestSessionStatus.Ok) { - requestSession.status = RequestSessionStatus.Errored; + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; } } @@ -74,8 +74,8 @@ export class NodeClient extends BaseClient { // Ensure that this is happening within the bounds of a request, and make sure not to override // Session Status if Errored / Crashed - if (requestSession && requestSession.status === RequestSessionStatus.Ok) { - requestSession.status = RequestSessionStatus.Errored; + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; } } } diff --git a/packages/node/src/handlers.ts b/packages/node/src/handlers.ts index c8156896acc8..332d8593010a 100644 --- a/packages/node/src/handlers.ts +++ b/packages/node/src/handlers.ts @@ -2,7 +2,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { captureException, getCurrentHub, startTransaction, withScope } from '@sentry/core'; import { extractTraceparentData, Span } from '@sentry/tracing'; -import { Event, ExtractedNodeRequestData, RequestSessionStatus, Transaction } from '@sentry/types'; +import { Event, ExtractedNodeRequestData, Transaction } from '@sentry/types'; import { isPlainObject, isString, logger, normalize, stripUrlQueryAndFragment } from '@sentry/utils'; import * as cookie from 'cookie'; import * as domain from 'domain'; @@ -424,7 +424,7 @@ export function requestHandler( const scope = currentHub.getScope(); if (scope) { // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); } } }); @@ -517,8 +517,9 @@ export function errorHandler(options?: { // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) - requestSession.status = RequestSessionStatus.Crashed; + if (requestSession && requestSession.status !== undefined) { + requestSession.status = 'crashed'; + } } } diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index b3bae88dfa8a..8aa44c75912b 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -5,12 +5,12 @@ export { SdkInfo, Event, EventHint, + EventStatus, Exception, Response, - Severity, + SeverityLevel, StackFrame, Stacktrace, - Status, Thread, User, } from '@sentry/types'; diff --git a/packages/node/src/integrations/console.ts b/packages/node/src/integrations/console.ts index 1dfcf0a98cbe..0f19f15ffeb7 100644 --- a/packages/node/src/integrations/console.ts +++ b/packages/node/src/integrations/console.ts @@ -1,6 +1,6 @@ import { getCurrentHub } from '@sentry/core'; -import { Integration, Severity } from '@sentry/types'; -import { fill } from '@sentry/utils'; +import { Integration } from '@sentry/types'; +import { fill, severityFromString } from '@sentry/utils'; import * as util from 'util'; /** Console module integration */ @@ -30,24 +30,7 @@ export class Console implements Integration { */ function createConsoleWrapper(level: string): (originalConsoleMethod: () => void) => void { return function consoleWrapper(originalConsoleMethod: () => void): () => void { - let sentryLevel: Severity; - - switch (level) { - case 'debug': - sentryLevel = Severity.Debug; - break; - case 'error': - sentryLevel = Severity.Error; - break; - case 'info': - sentryLevel = Severity.Info; - break; - case 'warn': - sentryLevel = Severity.Warning; - break; - default: - sentryLevel = Severity.Log; - } + const sentryLevel = severityFromString(level); /* eslint-disable prefer-rest-params */ return function(this: typeof console): void { diff --git a/packages/node/src/integrations/onuncaughtexception.ts b/packages/node/src/integrations/onuncaughtexception.ts index c5460adad25d..b9f1824a2f77 100644 --- a/packages/node/src/integrations/onuncaughtexception.ts +++ b/packages/node/src/integrations/onuncaughtexception.ts @@ -1,5 +1,5 @@ import { getCurrentHub, Scope } from '@sentry/core'; -import { Integration, Severity } from '@sentry/types'; +import { Integration } from '@sentry/types'; import { logger } from '@sentry/utils'; import { NodeClient } from '../client'; @@ -77,7 +77,7 @@ export class OnUncaughtException implements Integration { if (hub.getIntegration(OnUncaughtException)) { hub.withScope((scope: Scope) => { - scope.setLevel(Severity.Fatal); + scope.setLevel('fatal'); hub.captureException(error, { originalException: error, data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, diff --git a/packages/node/src/sdk.ts b/packages/node/src/sdk.ts index 7fbd6ba479be..52d137277fd8 100644 --- a/packages/node/src/sdk.ts +++ b/packages/node/src/sdk.ts @@ -232,7 +232,7 @@ function startSessionTracking(): void { // Ref: https://nodejs.org/api/process.html#process_event_beforeexit process.on('beforeExit', () => { const session = hub.getScope()?.getSession(); - const terminalStates = [SessionStatus.Exited, SessionStatus.Crashed]; + const terminalStates: SessionStatus[] = ['exited', 'crashed']; // Only call endSession, if the Session exists on Scope and SessionStatus is not a // Terminal Status i.e. Exited or Crashed because // "When a session is moved away from ok it must not be updated anymore." diff --git a/packages/node/src/transports/base/index.ts b/packages/node/src/transports/base/index.ts index 11260113ab62..42376ec653e5 100644 --- a/packages/node/src/transports/base/index.ts +++ b/packages/node/src/transports/base/index.ts @@ -7,11 +7,10 @@ import { SentryRequestType, Session, SessionAggregates, - Status, Transport, TransportOptions, } from '@sentry/types'; -import { logger, parseRetryAfterHeader, PromiseBuffer, SentryError } from '@sentry/utils'; +import { eventStatusFromHttpCode, logger, parseRetryAfterHeader, PromiseBuffer, SentryError } from '@sentry/utils'; import * as fs from 'fs'; import * as http from 'http'; import * as https from 'https'; @@ -209,7 +208,7 @@ export abstract class BaseTransport implements Transport { const options = this._getRequestOptions(this.urlParser(sentryRequest.url)); const req = this.module.request(options, res => { const statusCode = res.statusCode || 500; - const status = Status.fromHttpCode(statusCode); + const status = eventStatusFromHttpCode(statusCode); res.setEncoding('utf8'); @@ -236,7 +235,7 @@ export abstract class BaseTransport implements Transport { )}`, ); - if (status === Status.Success) { + if (status === 'success') { resolve({ status }); } else { let rejectionMessage = `HTTP Error (${statusCode})`; diff --git a/packages/node/test/client.test.ts b/packages/node/test/client.test.ts index 1ff6dc73d03e..f18f66c716af 100644 --- a/packages/node/test/client.test.ts +++ b/packages/node/test/client.test.ts @@ -1,5 +1,4 @@ import { Scope, SessionFlusher } from '@sentry/hub'; -import { RequestSessionStatus } from '@sentry/types'; import { NodeClient } from '../src'; @@ -17,12 +16,12 @@ describe('NodeClient', () => { test('when autoSessionTracking is enabled, and requestHandler is not used -> requestStatus should not be set', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: true, release: '1.4' }); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureException(new Error('test exception'), undefined, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); test('when autoSessionTracking is disabled -> requestStatus should not be set', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: false, release: '1.4' }); @@ -31,12 +30,12 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureException(new Error('test exception'), undefined, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); test('when autoSessionTracking is enabled + requestSession status is Crashed -> requestStatus should not be overridden', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: true, release: '1.4' }); @@ -45,12 +44,12 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Crashed }); + scope.setRequestSession({ status: 'crashed' }); client.captureException(new Error('test exception'), undefined, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Crashed); + expect(requestSession!.status).toEqual('crashed'); }); test('when autoSessionTracking is enabled + error occurs within request bounds -> requestStatus should be set to Errored', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: true, release: '1.4' }); @@ -59,12 +58,12 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureException(new Error('test exception'), undefined, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Errored); + expect(requestSession!.status).toEqual('errored'); }); test('when autoSessionTracking is enabled + error occurs outside of request bounds -> requestStatus should not be set to Errored', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: true, release: '1.4' }); @@ -89,7 +88,7 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureEvent( { message: 'message', exception: { values: [{ type: 'exception type 1' }] } }, undefined, @@ -97,7 +96,7 @@ describe('NodeClient', () => { ); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); test('When captureEvent is called with an exception, requestSession status should be set to Errored', () => { @@ -107,12 +106,12 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureEvent({ message: 'message', exception: { values: [{ type: 'exception type 1' }] } }, {}, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Errored); + expect(requestSession!.status).toEqual('errored'); }); test('When captureEvent is called without an exception, requestSession status should not be set to Errored', () => { @@ -122,12 +121,12 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureEvent({ message: 'message' }, {}, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); test('When captureEvent is called with an exception but outside of a request, then requestStatus should not be set', () => { @@ -154,18 +153,18 @@ describe('NodeClient', () => { client.initSessionFlusher(); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureEvent({ message: 'message', type: 'transaction' }, undefined, scope); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); test('When captureEvent is called with an exception but requestHandler is not used, then requestSession status should not be set', () => { client = new NodeClient({ dsn: PUBLIC_DSN, autoSessionTracking: true, release: '1.3' }); const scope = new Scope(); - scope.setRequestSession({ status: RequestSessionStatus.Ok }); + scope.setRequestSession({ status: 'ok' }); client.captureEvent( { message: 'message', exception: { values: [{ type: 'exception type 1' }] } }, undefined, @@ -173,7 +172,7 @@ describe('NodeClient', () => { ); const requestSession = scope.getRequestSession(); - expect(requestSession!.status).toEqual(RequestSessionStatus.Ok); + expect(requestSession!.status).toEqual('ok'); }); }); }); diff --git a/packages/node/test/handlers.test.ts b/packages/node/test/handlers.test.ts index 4a2b060c887b..daef81e4d44c 100644 --- a/packages/node/test/handlers.test.ts +++ b/packages/node/test/handlers.test.ts @@ -1,8 +1,8 @@ import * as sentryCore from '@sentry/core'; import { Hub } from '@sentry/hub'; import * as sentryHub from '@sentry/hub'; -import { SpanStatus, Transaction } from '@sentry/tracing'; -import { RequestSessionStatus, Runtime } from '@sentry/types'; +import { Transaction } from '@sentry/tracing'; +import { Runtime } from '@sentry/types'; import * as http from 'http'; import * as net from 'net'; @@ -229,7 +229,7 @@ describe('requestHandler', () => { sentryRequestMiddleware(req, res, next); const scope = sentryCore.getCurrentHub().getScope(); - expect(scope?.getRequestSession()).toEqual({ status: RequestSessionStatus.Ok }); + expect(scope?.getRequestSession()).toEqual({ status: 'ok' }); }); it('autoSessionTracking is disabled, does not set requestSession, when handling a request', () => { @@ -258,7 +258,7 @@ describe('requestHandler', () => { res.emit('finish'); setImmediate(() => { - expect(scope?.getRequestSession()).toEqual({ status: RequestSessionStatus.Ok }); + expect(scope?.getRequestSession()).toEqual({ status: 'ok' }); expect(captureRequestSession).toHaveBeenCalled(); done(); }); @@ -403,7 +403,7 @@ describe('tracingHandler', () => { setImmediate(() => { expect(finishTransaction).toHaveBeenCalled(); - expect(transaction.status).toBe(SpanStatus.Ok); + expect(transaction.status).toBe('ok'); expect(transaction.tags).toEqual(expect.objectContaining({ 'http.status_code': '200' })); done(); }); @@ -708,10 +708,10 @@ describe('errorHandler()', () => { jest.spyOn(sentryCore, 'getCurrentHub').mockReturnValue(hub); jest.spyOn(sentryHub, 'getCurrentHub').mockReturnValue(hub); - scope?.setRequestSession({ status: RequestSessionStatus.Ok }); + scope?.setRequestSession({ status: 'ok' }); sentryErrorMiddleware({ name: 'error', message: 'this is an error' }, req, res, next); const requestSession = scope?.getRequestSession(); - expect(requestSession).toEqual({ status: RequestSessionStatus.Ok }); + expect(requestSession).toEqual({ status: 'ok' }); }); it('autoSessionTracking is enabled + requestHandler is not used -> does not set requestSession status on Crash', () => { @@ -724,10 +724,10 @@ describe('errorHandler()', () => { jest.spyOn(sentryCore, 'getCurrentHub').mockReturnValue(hub); jest.spyOn(sentryHub, 'getCurrentHub').mockReturnValue(hub); - scope?.setRequestSession({ status: RequestSessionStatus.Ok }); + scope?.setRequestSession({ status: 'ok' }); sentryErrorMiddleware({ name: 'error', message: 'this is an error' }, req, res, next); const requestSession = scope?.getRequestSession(); - expect(requestSession).toEqual({ status: RequestSessionStatus.Ok }); + expect(requestSession).toEqual({ status: 'ok' }); }); it('when autoSessionTracking is enabled, should set requestSession status to Crashed when an unhandled error occurs within the bounds of a request', () => { @@ -742,10 +742,10 @@ describe('errorHandler()', () => { jest.spyOn(sentryCore, 'getCurrentHub').mockReturnValue(hub); jest.spyOn(sentryHub, 'getCurrentHub').mockReturnValue(hub); - scope?.setRequestSession({ status: RequestSessionStatus.Ok }); + scope?.setRequestSession({ status: 'ok' }); sentryErrorMiddleware({ name: 'error', message: 'this is an error' }, req, res, next); const requestSession = scope?.getRequestSession(); - expect(requestSession).toEqual({ status: RequestSessionStatus.Crashed }); + expect(requestSession).toEqual({ status: 'crashed' }); }); it('when autoSessionTracking is enabled, should not set requestSession status on Crash when it occurs outside the bounds of a request', () => { diff --git a/packages/node/test/transports/http.test.ts b/packages/node/test/transports/http.test.ts index 60ebadf015ef..d4d8e53d734c 100644 --- a/packages/node/test/transports/http.test.ts +++ b/packages/node/test/transports/http.test.ts @@ -1,5 +1,5 @@ import { Session } from '@sentry/hub'; -import { Event, SessionAggregates, SessionStatus, Status, TransportOptions } from '@sentry/types'; +import { Event, SessionAggregates, TransportOptions } from '@sentry/types'; import { SentryError } from '@sentry/utils'; import * as http from 'http'; import * as HttpsProxyAgent from 'https-proxy-agent'; @@ -27,7 +27,7 @@ const sessionPayload: Session = { timestamp: Date.now(), init: true, duration: 0, - status: SessionStatus.Exited, + status: 'exited', update: jest.fn(), close: jest.fn(), toJSON: jest.fn(), @@ -284,10 +284,10 @@ describe('HTTPTransport', () => { mockReturnCode = 200; const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toEqual(Status.Success); + expect(transactionRes.status).toEqual('success'); mock.mockRestore(); }); @@ -331,10 +331,10 @@ describe('HTTPTransport', () => { mockReturnCode = 200; const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toEqual(Status.Success); + expect(transactionRes.status).toEqual('success'); const sessionsRes = await transport.sendSession(sessionPayload); - expect(sessionsRes.status).toEqual(Status.Success); + expect(sessionsRes.status).toEqual('success'); try { await transport.sendEvent(eventPayload); @@ -350,7 +350,7 @@ describe('HTTPTransport', () => { } const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); mock.mockRestore(); }); @@ -439,13 +439,13 @@ describe('HTTPTransport', () => { mockReturnCode = 200; const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); const sessionsRes = await transport.sendSession(sessionPayload); - expect(sessionsRes.status).toEqual(Status.Success); + expect(sessionsRes.status).toEqual('success'); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toEqual(Status.Success); + expect(transactionRes.status).toEqual('success'); mock.mockRestore(); }); @@ -513,10 +513,10 @@ describe('HTTPTransport', () => { mockReturnCode = 200; const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toEqual(Status.Success); + expect(transactionRes.status).toEqual('success'); mock.mockRestore(); }); @@ -569,10 +569,10 @@ describe('HTTPTransport', () => { mockReturnCode = 200; const transactionRes = await transport.sendEvent(transactionPayload); - expect(transactionRes.status).toEqual(Status.Success); + expect(transactionRes.status).toEqual('success'); const eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); mock.mockRestore(); }); @@ -599,7 +599,7 @@ describe('HTTPTransport', () => { .mockReturnValueOnce(now + retryAfterSeconds * 1000); let eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); try { await transport.sendEvent(eventPayload); @@ -618,7 +618,7 @@ describe('HTTPTransport', () => { mockHeaders = {}; eventRes = await transport.sendEvent(eventPayload); - expect(eventRes.status).toEqual(Status.Success); + expect(eventRes.status).toEqual('success'); mock.mockRestore(); }); diff --git a/packages/serverless/src/awslambda.ts b/packages/serverless/src/awslambda.ts index 70b09d3cc97c..6001613a91de 100644 --- a/packages/serverless/src/awslambda.ts +++ b/packages/serverless/src/awslambda.ts @@ -6,7 +6,6 @@ import { flush, getCurrentHub, Scope, - Severity, startTransaction, withScope, } from '@sentry/node'; @@ -275,7 +274,7 @@ export function wrapHandler( timeoutWarningTimer = setTimeout(() => { withScope(scope => { scope.setTag('timeout', humanReadableTimeout); - captureMessage(`Possible function timeout: ${context.functionName}`, Severity.Warning); + captureMessage(`Possible function timeout: ${context.functionName}`, 'warning'); }); }, timeoutWarningDelay); } diff --git a/packages/tracing/src/browser/backgroundtab.ts b/packages/tracing/src/browser/backgroundtab.ts index d2c3d55eeb86..3701404b5d26 100644 --- a/packages/tracing/src/browser/backgroundtab.ts +++ b/packages/tracing/src/browser/backgroundtab.ts @@ -2,7 +2,7 @@ import { getGlobalObject, logger } from '@sentry/utils'; import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants'; import { IdleTransaction } from '../idletransaction'; -import { SpanStatus } from '../spanstatus'; +import { SpanStatusType } from '../span'; import { getActiveTransaction } from '../utils'; const global = getGlobalObject(); @@ -16,13 +16,15 @@ export function registerBackgroundTabDetection(): void { global.document.addEventListener('visibilitychange', () => { const activeTransaction = getActiveTransaction() as IdleTransaction; if (global.document.hidden && activeTransaction) { + const statusType: SpanStatusType = 'cancelled'; + logger.log( - `[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background, op: ${activeTransaction.op}`, + `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`, ); // We should not set status if it is already set, this prevent important statuses like // error or data loss from being overwritten on transaction. if (!activeTransaction.status) { - activeTransaction.setStatus(SpanStatus.Cancelled); + activeTransaction.setStatus(statusType); } activeTransaction.setTag('visibilitychange', 'document.hidden'); activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]); diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 5fda84855208..4218f8e84fd7 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -4,7 +4,6 @@ import { getGlobalObject, logger } from '@sentry/utils'; import { startIdleTransaction } from '../hubextensions'; import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction'; -import { SpanStatus } from '../spanstatus'; import { extractTraceparentData, secToMs } from '../utils'; import { registerBackgroundTabDetection } from './backgroundtab'; import { MetricsInstrumentation } from './metrics'; @@ -269,7 +268,7 @@ function adjustTransactionDuration(maxDuration: number, transaction: IdleTransac const diff = endTimestamp - transaction.startTimestamp; const isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0); if (isOutdatedTransaction) { - transaction.setStatus(SpanStatus.DeadlineExceeded); + transaction.setStatus('deadline_exceeded'); transaction.setTag('maxTransactionDurationExceeded', 'true'); } } diff --git a/packages/tracing/src/browser/request.ts b/packages/tracing/src/browser/request.ts index db9bf8066314..2094d2052292 100644 --- a/packages/tracing/src/browser/request.ts +++ b/packages/tracing/src/browser/request.ts @@ -1,7 +1,6 @@ import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils'; import { Span } from '../span'; -import { SpanStatus } from '../spanstatus'; import { getActiveTransaction, hasTracingEnabled } from '../utils'; export const DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; @@ -156,7 +155,7 @@ export function fetchCallback( // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access span.setHttpStatus(handlerData.response.status); } else if (handlerData.error) { - span.setStatus(SpanStatus.InternalError); + span.setStatus('internal_error'); } span.finish(); diff --git a/packages/tracing/src/errors.ts b/packages/tracing/src/errors.ts index eb15d592cb7c..e63e4d4244aa 100644 --- a/packages/tracing/src/errors.ts +++ b/packages/tracing/src/errors.ts @@ -1,6 +1,6 @@ import { addInstrumentationHandler, logger } from '@sentry/utils'; -import { SpanStatus } from './spanstatus'; +import { SpanStatusType } from './span'; import { getActiveTransaction } from './utils'; /** @@ -23,7 +23,8 @@ export function registerErrorInstrumentation(): void { function errorCallback(): void { const activeTransaction = getActiveTransaction(); if (activeTransaction) { - logger.log(`[Tracing] Transaction: ${SpanStatus.InternalError} -> Global error occured`); - activeTransaction.setStatus(SpanStatus.InternalError); + const status: SpanStatusType = 'internal_error'; + logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); + activeTransaction.setStatus(status); } } diff --git a/packages/tracing/src/hubextensions.ts b/packages/tracing/src/hubextensions.ts index a70aa01e18a5..7bc654094ef7 100644 --- a/packages/tracing/src/hubextensions.ts +++ b/packages/tracing/src/hubextensions.ts @@ -6,7 +6,6 @@ import { Options, SamplingContext, TransactionContext, - TransactionSamplingMethod, } from '@sentry/types'; import { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils'; @@ -51,7 +50,7 @@ function sample(transaction: T, options: Options, samplin // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that if (transaction.sampled !== undefined) { transaction.setMetadata({ - transactionSampling: { method: TransactionSamplingMethod.Explicit }, + transactionSampling: { method: 'explicitly_set' }, }); return transaction; } @@ -63,7 +62,7 @@ function sample(transaction: T, options: Options, samplin sampleRate = options.tracesSampler(samplingContext); transaction.setMetadata({ transactionSampling: { - method: TransactionSamplingMethod.Sampler, + method: 'client_sampler', // cast to number in case it's a boolean rate: Number(sampleRate), }, @@ -71,13 +70,13 @@ function sample(transaction: T, options: Options, samplin } else if (samplingContext.parentSampled !== undefined) { sampleRate = samplingContext.parentSampled; transaction.setMetadata({ - transactionSampling: { method: TransactionSamplingMethod.Inheritance }, + transactionSampling: { method: 'inheritance' }, }); } else { sampleRate = options.tracesSampleRate; transaction.setMetadata({ transactionSampling: { - method: TransactionSamplingMethod.Rate, + method: 'client_rate', // cast to number in case it's a boolean rate: Number(sampleRate), }, diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts index c14e079b50c2..07839d6c6616 100644 --- a/packages/tracing/src/idletransaction.ts +++ b/packages/tracing/src/idletransaction.ts @@ -4,7 +4,6 @@ import { logger, timestampWithMs } from '@sentry/utils'; import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from './constants'; import { Span, SpanRecorder } from './span'; -import { SpanStatus } from './spanstatus'; import { Transaction } from './transaction'; export const DEFAULT_IDLE_TIMEOUT = 1000; @@ -125,7 +124,7 @@ export class IdleTransaction extends Transaction { // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early if (!span.endTimestamp) { span.endTimestamp = endTimestamp; - span.setStatus(SpanStatus.Cancelled); + span.setStatus('cancelled'); logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); } @@ -253,7 +252,7 @@ export class IdleTransaction extends Transaction { if (this._heartbeatCounter >= 3) { logger.log(`[Tracing] Transaction finished because of no change for 3 heart beats`); - this.setStatus(SpanStatus.DeadlineExceeded); + this.setStatus('deadline_exceeded'); this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]); this.finish(); } else { diff --git a/packages/tracing/src/index.bundle.ts b/packages/tracing/src/index.bundle.ts index 5b2bfd00501b..bd5def4692a9 100644 --- a/packages/tracing/src/index.bundle.ts +++ b/packages/tracing/src/index.bundle.ts @@ -3,12 +3,12 @@ export { Request, SdkInfo, Event, + EventStatus, Exception, Response, - Severity, + SeverityLevel, StackFrame, Stacktrace, - Status, Thread, User, } from '@sentry/types'; diff --git a/packages/tracing/src/index.ts b/packages/tracing/src/index.ts index 1974227b2ff1..5bb593e01109 100644 --- a/packages/tracing/src/index.ts +++ b/packages/tracing/src/index.ts @@ -21,7 +21,7 @@ export { Integrations }; // For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts export { BrowserTracing } from './browser'; -export { Span } from './span'; +export { Span, SpanStatusType, spanStatusfromHttpCode } from './span'; export { Transaction } from './transaction'; export { // TODO deprecate old name in v7 @@ -29,7 +29,6 @@ export { RequestInstrumentationOptions, defaultRequestInstrumentationOptions, } from './browser'; -export { SpanStatus } from './spanstatus'; export { IdleTransaction } from './idletransaction'; export { startIdleTransaction } from './hubextensions'; diff --git a/packages/tracing/src/span.ts b/packages/tracing/src/span.ts index ed3c03651ba0..990f56ce981c 100644 --- a/packages/tracing/src/span.ts +++ b/packages/tracing/src/span.ts @@ -2,8 +2,6 @@ import { Primitive, Span as SpanInterface, SpanContext, Transaction } from '@sentry/types'; import { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils'; -import { SpanStatus } from './spanstatus'; - /** * Keeps track of finished spans for a given transaction * @internal @@ -56,7 +54,7 @@ export class Span implements SpanInterface { /** * Internal keeper of the status */ - public status?: SpanStatus | string; + public status?: SpanStatusType | string; /** * @inheritDoc @@ -204,7 +202,7 @@ export class Span implements SpanInterface { /** * @inheritDoc */ - public setStatus(value: SpanStatus): this { + public setStatus(value: SpanStatusType): this { this.status = value; return this; } @@ -214,8 +212,8 @@ export class Span implements SpanInterface { */ public setHttpStatus(httpStatus: number): this { this.setTag('http.status_code', String(httpStatus)); - const spanStatus = SpanStatus.fromHttpCode(httpStatus); - if (spanStatus !== SpanStatus.UnknownError) { + const spanStatus = spanStatusfromHttpCode(httpStatus); + if (spanStatus !== 'unknown_error') { this.setStatus(spanStatus); } return this; @@ -225,7 +223,7 @@ export class Span implements SpanInterface { * @inheritDoc */ public isSuccess(): boolean { - return this.status === SpanStatus.Ok; + return this.status === 'ok'; } /** @@ -340,3 +338,85 @@ export class Span implements SpanInterface { }); } } + +export type SpanStatusType = + /** The operation completed successfully. */ + | 'ok' + /** Deadline expired before operation could complete. */ + | 'deadline_exceeded' + /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ + | 'unauthenticated' + /** 403 Forbidden */ + | 'permission_denied' + /** 404 Not Found. Some requested entity (file or directory) was not found. */ + | 'not_found' + /** 429 Too Many Requests */ + | 'resource_exhausted' + /** Client specified an invalid argument. 4xx. */ + | 'invalid_argument' + /** 501 Not Implemented */ + | 'unimplemented' + /** 503 Service Unavailable */ + | 'unavailable' + /** Other/generic 5xx. */ + | 'internal_error' + /** Unknown. Any non-standard HTTP status code. */ + | 'unknown_error' + /** The operation was cancelled (typically by the user). */ + | 'cancelled' + /** Already exists (409) */ + | 'already_exists' + /** Operation was rejected because the system is not in a state required for the operation's */ + | 'failed_precondition' + /** The operation was aborted, typically due to a concurrency issue. */ + | 'aborted' + /** Operation was attempted past the valid range. */ + | 'out_of_range' + /** Unrecoverable data loss or corruption */ + | 'data_loss'; + +/** + * Converts a HTTP status code into a {@link SpanStatusType}. + * + * @param httpStatus The HTTP response status code. + * @returns The span status or unknown_error. + */ +export function spanStatusfromHttpCode(httpStatus: number): SpanStatusType { + if (httpStatus < 400 && httpStatus >= 100) { + return 'ok'; + } + + if (httpStatus >= 400 && httpStatus < 500) { + switch (httpStatus) { + case 401: + return 'unauthenticated'; + case 403: + return 'permission_denied'; + case 404: + return 'not_found'; + case 409: + return 'already_exists'; + case 413: + return 'failed_precondition'; + case 429: + return 'resource_exhausted'; + default: + return 'invalid_argument'; + } + } + + if (httpStatus >= 500 && httpStatus < 600) { + switch (httpStatus) { + case 501: + return 'unimplemented'; + case 503: + return 'unavailable'; + case 504: + return 'deadline_exceeded'; + default: + return 'internal_error'; + } + } + + return 'unknown_error'; +} diff --git a/packages/tracing/src/spanstatus.ts b/packages/tracing/src/spanstatus.ts index 692b60d7d364..6191b27f148c 100644 --- a/packages/tracing/src/spanstatus.ts +++ b/packages/tracing/src/spanstatus.ts @@ -36,52 +36,3 @@ export enum SpanStatus { /** Unrecoverable data loss or corruption */ DataLoss = 'data_loss', } - -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -export namespace SpanStatus { - /** - * Converts a HTTP status code into a {@link SpanStatus}. - * - * @param httpStatus The HTTP response status code. - * @returns The span status or {@link SpanStatus.UnknownError}. - */ - export function fromHttpCode(httpStatus: number): SpanStatus { - if (httpStatus < 400 && httpStatus >= 100) { - return SpanStatus.Ok; - } - - if (httpStatus >= 400 && httpStatus < 500) { - switch (httpStatus) { - case 401: - return SpanStatus.Unauthenticated; - case 403: - return SpanStatus.PermissionDenied; - case 404: - return SpanStatus.NotFound; - case 409: - return SpanStatus.AlreadyExists; - case 413: - return SpanStatus.FailedPrecondition; - case 429: - return SpanStatus.ResourceExhausted; - default: - return SpanStatus.InvalidArgument; - } - } - - if (httpStatus >= 500 && httpStatus < 600) { - switch (httpStatus) { - case 501: - return SpanStatus.Unimplemented; - case 503: - return SpanStatus.Unavailable; - case 504: - return SpanStatus.DeadlineExceeded; - default: - return SpanStatus.InternalError; - } - } - - return SpanStatus.UnknownError; - } -} diff --git a/packages/tracing/src/transaction.ts b/packages/tracing/src/transaction.ts index 45cb41357863..5143881ab159 100644 --- a/packages/tracing/src/transaction.ts +++ b/packages/tracing/src/transaction.ts @@ -2,7 +2,6 @@ import { getCurrentHub, Hub } from '@sentry/hub'; import { Event, Measurements, - Outcome, Transaction as TransactionInterface, TransactionContext, TransactionMetadata, @@ -107,7 +106,7 @@ export class Transaction extends SpanClass implements TransactionInterface { const client = this._hub.getClient(); const transport = client && client.getTransport && client.getTransport(); if (transport && transport.recordLostEvent) { - transport.recordLostEvent(Outcome.SampleRate, 'transaction'); + transport.recordLostEvent('sample_rate', 'transaction'); } return undefined; } diff --git a/packages/tracing/test/browser/backgroundtab.test.ts b/packages/tracing/test/browser/backgroundtab.test.ts index 71b8810c9142..e46c79695d20 100644 --- a/packages/tracing/test/browser/backgroundtab.test.ts +++ b/packages/tracing/test/browser/backgroundtab.test.ts @@ -2,8 +2,8 @@ import { BrowserClient } from '@sentry/browser'; import { Hub, makeMain } from '@sentry/hub'; import { JSDOM } from 'jsdom'; -import { SpanStatus } from '../../src'; import { registerBackgroundTabDetection } from '../../src/browser/backgroundtab'; +import { addExtensionMethods } from '../../src/hubextensions'; describe('registerBackgroundTabDetection', () => { let events: Record = {}; @@ -16,6 +16,9 @@ describe('registerBackgroundTabDetection', () => { hub = new Hub(new BrowserClient({ tracesSampleRate: 1 })); makeMain(hub); + // If we do not add extension methods, invoking hub.startTransaction returns undefined + addExtensionMethods(); + // @ts-ignore need to override global document global.document.addEventListener = jest.fn((event, callback) => { events[event] = callback; @@ -49,7 +52,7 @@ describe('registerBackgroundTabDetection', () => { global.document.hidden = true; events.visibilitychange(); - expect(transaction.status).toBe(SpanStatus.Cancelled); + expect(transaction.status).toBe('cancelled'); expect(transaction.tags.visibilitychange).toBe('document.hidden'); expect(transaction.endTimestamp).toBeDefined(); }); diff --git a/packages/tracing/test/browser/browsertracing.test.ts b/packages/tracing/test/browser/browsertracing.test.ts index e8a123eeb93c..4b89082f2942 100644 --- a/packages/tracing/test/browser/browsertracing.test.ts +++ b/packages/tracing/test/browser/browsertracing.test.ts @@ -3,7 +3,6 @@ import { Hub, makeMain } from '@sentry/hub'; import { getGlobalObject } from '@sentry/utils'; import { JSDOM } from 'jsdom'; -import { SpanStatus } from '../../src'; import { BrowserTracing, BrowserTracingOptions, @@ -273,7 +272,7 @@ describe('BrowserTracing', () => { const transaction = getActiveTransaction(hub) as IdleTransaction; transaction.finish(transaction.startTimestamp + secToMs(DEFAULT_MAX_TRANSACTION_DURATION_SECONDS) + 1); - expect(transaction.status).toBe(SpanStatus.DeadlineExceeded); + expect(transaction.status).toBe('deadline_exceeded'); expect(transaction.tags.maxTransactionDurationExceeded).toBeDefined(); }); diff --git a/packages/tracing/test/browser/request.test.ts b/packages/tracing/test/browser/request.test.ts index 4c2a18788131..dce4b0874393 100644 --- a/packages/tracing/test/browser/request.test.ts +++ b/packages/tracing/test/browser/request.test.ts @@ -2,7 +2,7 @@ import { BrowserClient } from '@sentry/browser'; import { Hub, makeMain } from '@sentry/hub'; import * as utils from '@sentry/utils'; -import { Span, SpanStatus, Transaction } from '../../src'; +import { Span, spanStatusfromHttpCode, Transaction } from '../../src'; import { fetchCallback, FetchData, instrumentOutgoingRequests, xhrCallback, XHRData } from '../../src/browser/request'; import { addExtensionMethods } from '../../src/hubextensions'; import * as tracingUtils from '../../src/utils'; @@ -176,7 +176,7 @@ describe('callbacks', () => { // triggered by response coming back fetchCallback(postRequestFetchHandlerData, alwaysCreateSpan, spans); - expect(newSpan!.status).toBe(SpanStatus.fromHttpCode(404)); + expect(newSpan!.status).toBe(spanStatusfromHttpCode(404)); }); it('adds sentry-trace header to fetch requests', () => { @@ -267,7 +267,7 @@ describe('callbacks', () => { // triggered by response coming back xhrCallback(postRequestXHRHandlerData, alwaysCreateSpan, spans); - expect(newSpan!.status).toBe(SpanStatus.fromHttpCode(404)); + expect(newSpan!.status).toBe(spanStatusfromHttpCode(404)); }); }); }); diff --git a/packages/tracing/test/errors.test.ts b/packages/tracing/test/errors.test.ts index 5a0477cb9d31..baebec2bab86 100644 --- a/packages/tracing/test/errors.test.ts +++ b/packages/tracing/test/errors.test.ts @@ -1,7 +1,6 @@ import { BrowserClient } from '@sentry/browser'; import { Hub, makeMain } from '@sentry/hub'; -import { SpanStatus } from '../src'; import { registerErrorInstrumentation } from '../src/errors'; import { _addTracingExtensions } from '../src/hubextensions'; @@ -71,7 +70,7 @@ describe('registerErrorHandlers()', () => { hub.configureScope(scope => scope.setSpan(transaction)); mockErrorCallback(); - expect(transaction.status).toBe(SpanStatus.InternalError); + expect(transaction.status).toBe('internal_error'); transaction.finish(); }); @@ -82,7 +81,7 @@ describe('registerErrorHandlers()', () => { hub.configureScope(scope => scope.setSpan(transaction)); mockUnhandledRejectionCallback(); - expect(transaction.status).toBe(SpanStatus.InternalError); + expect(transaction.status).toBe('internal_error'); transaction.finish(); }); }); diff --git a/packages/tracing/test/hub.test.ts b/packages/tracing/test/hub.test.ts index 576cf0a34ca4..3f39bb985ca6 100644 --- a/packages/tracing/test/hub.test.ts +++ b/packages/tracing/test/hub.test.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/unbound-method */ import { BrowserClient } from '@sentry/browser'; import { Hub, makeMain } from '@sentry/hub'; -import { TransactionSamplingMethod } from '@sentry/types'; import * as utilsModule from '@sentry/utils'; // for mocking import { logger } from '@sentry/utils'; @@ -221,7 +220,7 @@ describe('Hub', () => { hub.startTransaction({ name: 'dogpark', sampled: true }); expect(Transaction.prototype.setMetadata).toHaveBeenCalledWith({ - transactionSampling: { method: TransactionSamplingMethod.Explicit }, + transactionSampling: { method: 'explicitly_set' }, }); }); @@ -232,7 +231,7 @@ describe('Hub', () => { hub.startTransaction({ name: 'dogpark' }); expect(Transaction.prototype.setMetadata).toHaveBeenCalledWith({ - transactionSampling: { method: TransactionSamplingMethod.Sampler, rate: 0.1121 }, + transactionSampling: { method: 'client_sampler', rate: 0.1121 }, }); }); @@ -242,7 +241,7 @@ describe('Hub', () => { hub.startTransaction({ name: 'dogpark', parentSampled: true }); expect(Transaction.prototype.setMetadata).toHaveBeenCalledWith({ - transactionSampling: { method: TransactionSamplingMethod.Inheritance }, + transactionSampling: { method: 'inheritance' }, }); }); @@ -252,7 +251,7 @@ describe('Hub', () => { hub.startTransaction({ name: 'dogpark' }); expect(Transaction.prototype.setMetadata).toHaveBeenCalledWith({ - transactionSampling: { method: TransactionSamplingMethod.Rate, rate: 0.1121 }, + transactionSampling: { method: 'client_rate', rate: 0.1121 }, }); }); }); diff --git a/packages/tracing/test/idletransaction.test.ts b/packages/tracing/test/idletransaction.test.ts index a7a29cf6ff86..b60fec726c54 100644 --- a/packages/tracing/test/idletransaction.test.ts +++ b/packages/tracing/test/idletransaction.test.ts @@ -1,6 +1,5 @@ import { BrowserClient, Transports } from '@sentry/browser'; import { Hub } from '@sentry/hub'; -import { Outcome } from '@sentry/types'; import { DEFAULT_IDLE_TIMEOUT, @@ -9,7 +8,6 @@ import { IdleTransactionSpanRecorder, } from '../src/idletransaction'; import { Span } from '../src/span'; -import { SpanStatus } from '../src/spanstatus'; export class SimpleTransport extends Transports.BaseTransport {} @@ -160,7 +158,7 @@ describe('IdleTransaction', () => { // Cancelled Span - has endtimestamp of transaction expect(spans[2].spanId).toBe(cancelledSpan.spanId); - expect(spans[2].status).toBe(SpanStatus.Cancelled); + expect(spans[2].status).toBe('cancelled'); expect(spans[2].endTimestamp).toBe(transaction.endTimestamp); } }); @@ -175,7 +173,7 @@ describe('IdleTransaction', () => { transaction.initSpanRecorder(10); transaction.finish(transaction.startTimestamp + 10); - expect(spy).toHaveBeenCalledWith(Outcome.SampleRate, 'transaction'); + expect(spy).toHaveBeenCalledWith('sample_rate', 'transaction'); }); describe('_initTimeout', () => { @@ -203,22 +201,22 @@ describe('IdleTransaction', () => { const transaction = new IdleTransaction({ name: 'foo' }, hub, 20000); const mockFinish = jest.spyOn(transaction, 'finish'); - expect(transaction.status).not.toEqual(SpanStatus.DeadlineExceeded); + expect(transaction.status).not.toEqual('deadline_exceeded'); expect(mockFinish).toHaveBeenCalledTimes(0); // Beat 1 jest.advanceTimersByTime(HEARTBEAT_INTERVAL); - expect(transaction.status).not.toEqual(SpanStatus.DeadlineExceeded); + expect(transaction.status).not.toEqual('deadline_exceeded'); expect(mockFinish).toHaveBeenCalledTimes(0); // Beat 2 jest.advanceTimersByTime(HEARTBEAT_INTERVAL); - expect(transaction.status).not.toEqual(SpanStatus.DeadlineExceeded); + expect(transaction.status).not.toEqual('deadline_exceeded'); expect(mockFinish).toHaveBeenCalledTimes(0); // Beat 3 jest.advanceTimersByTime(HEARTBEAT_INTERVAL); - expect(transaction.status).not.toEqual(SpanStatus.DeadlineExceeded); + expect(transaction.status).not.toEqual('deadline_exceeded'); expect(mockFinish).toHaveBeenCalledTimes(0); }); diff --git a/packages/tracing/test/span.test.ts b/packages/tracing/test/span.test.ts index 3690f13ce3f5..4b0887f2dda7 100644 --- a/packages/tracing/test/span.test.ts +++ b/packages/tracing/test/span.test.ts @@ -1,7 +1,7 @@ import { BrowserClient } from '@sentry/browser'; import { Hub, makeMain, Scope } from '@sentry/hub'; -import { Span, SpanStatus, Transaction } from '../src'; +import { Span, Transaction } from '../src'; import { TRACEPARENT_REGEXP } from '../src/utils'; describe('Span', () => { @@ -72,7 +72,7 @@ describe('Span', () => { describe('status', () => { test('setStatus', () => { const span = new Span({}); - span.setStatus(SpanStatus.PermissionDenied); + span.setStatus('permission_denied'); expect((span.getTraceContext() as any).status).toBe('permission_denied'); }); @@ -88,7 +88,7 @@ describe('Span', () => { expect(span.isSuccess()).toBe(false); span.setHttpStatus(200); expect(span.isSuccess()).toBe(true); - span.setStatus(SpanStatus.PermissionDenied); + span.setStatus('permission_denied'); expect(span.isSuccess()).toBe(false); span.setHttpStatus(0); expect(span.isSuccess()).toBe(false); @@ -287,14 +287,14 @@ describe('Span', () => { test('should have success status extracted from tags', () => { const span = new Span({}); - span.setStatus(SpanStatus.Ok); + span.setStatus('ok'); const context = span.getTraceContext(); expect((context as any).status).toBe('ok'); }); test('should have failure status extracted from tags', () => { const span = new Span({}); - span.setStatus(SpanStatus.ResourceExhausted); + span.setStatus('resource_exhausted'); const context = span.getTraceContext(); expect((context as any).status).toBe('resource_exhausted'); }); diff --git a/packages/types/src/breadcrumb.ts b/packages/types/src/breadcrumb.ts index cab5ac68b3e1..73f27c58a599 100644 --- a/packages/types/src/breadcrumb.ts +++ b/packages/types/src/breadcrumb.ts @@ -1,9 +1,9 @@ -import { Severity } from './severity'; +import { SeverityLevel } from './severity'; /** JSDoc */ export interface Breadcrumb { type?: string; - level?: Severity; + level?: SeverityLevel; event_id?: string; category?: string; message?: string; diff --git a/packages/types/src/client.ts b/packages/types/src/client.ts index 86263647d0d9..e71a3d2f39c6 100644 --- a/packages/types/src/client.ts +++ b/packages/types/src/client.ts @@ -4,7 +4,7 @@ import { Integration, IntegrationClass } from './integration'; import { Options } from './options'; import { Scope } from './scope'; import { Session } from './session'; -import { Severity } from './severity'; +import { SeverityLevel } from './severity'; import { Transport } from './transport'; /** @@ -36,7 +36,7 @@ export interface Client { * @param scope An optional scope containing event metadata. * @returns The event id */ - captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined; + captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string | undefined; /** * Captures a manually created event and sends it to Sentry. diff --git a/packages/types/src/event.ts b/packages/types/src/event.ts index 6abc13e82edb..67f6d9358792 100644 --- a/packages/types/src/event.ts +++ b/packages/types/src/event.ts @@ -7,7 +7,7 @@ import { Primitive } from './misc'; import { Request } from './request'; import { CaptureContext } from './scope'; import { SdkInfo } from './sdkinfo'; -import { Severity } from './severity'; +import { SeverityLevel } from './severity'; import { Span } from './span'; import { Stacktrace } from './stacktrace'; import { Measurements } from './transaction'; @@ -19,7 +19,7 @@ export interface Event { message?: string; timestamp?: number; start_timestamp?: number; - level?: Severity; + level?: SeverityLevel; platform?: string; logger?: string; server_name?: string; diff --git a/packages/types/src/eventstatus.ts b/packages/types/src/eventstatus.ts new file mode 100644 index 000000000000..498f0f45b3dd --- /dev/null +++ b/packages/types/src/eventstatus.ts @@ -0,0 +1,13 @@ +export type EventStatus = + /** The status could not be determined. */ + | 'unknown' + /** The event was skipped due to configuration or callbacks. */ + | 'skipped' + /** The event was sent to Sentry successfully. */ + | 'rate_limit' + /** The client is currently rate limited and will try again later. */ + | 'invalid' + /** The event could not be processed. */ + | 'failed' + /** A server-side error occurred during submission. */ + | 'success'; diff --git a/packages/types/src/hub.ts b/packages/types/src/hub.ts index a6be3e203db6..dd3bc1d5b2ab 100644 --- a/packages/types/src/hub.ts +++ b/packages/types/src/hub.ts @@ -6,7 +6,7 @@ import { Integration, IntegrationClass } from './integration'; import { Primitive } from './misc'; import { Scope } from './scope'; import { Session, SessionContext } from './session'; -import { Severity } from './severity'; +import { SeverityLevel } from './severity'; import { Span, SpanContext } from './span'; import { CustomSamplingContext, Transaction, TransactionContext } from './transaction'; import { User } from './user'; @@ -88,7 +88,7 @@ export interface Hub { * @param hint May contain additional information about the original exception. * @returns The generated eventId. */ - captureMessage(message: string, level?: Severity, hint?: EventHint): string; + captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string; /** * Captures a manually created event and sends it to Sentry. diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 2e67fc1e31f5..fdc33cac2d1f 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -5,12 +5,12 @@ export { Dsn, DsnComponents, DsnLike, DsnProtocol } from './dsn'; export { DebugImage, DebugImageType, DebugMeta } from './debugMeta'; export { ExtendedError } from './error'; export { Event, EventHint } from './event'; +export { EventStatus } from './eventstatus'; export { EventProcessor } from './eventprocessor'; export { Exception } from './exception'; export { Extra, Extras } from './extra'; export { Hub } from './hub'; export { Integration, IntegrationClass } from './integration'; -export { LogLevel } from './loglevel'; export { Mechanism } from './mechanism'; export { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc'; export { Options } from './options'; @@ -31,11 +31,13 @@ export { RequestSessionStatus, SessionFlusherLike, } from './session'; + +/* eslint-disable-next-line deprecation/deprecation */ export { Severity } from './severity'; +export { SeverityLevel, SeverityLevels } from './severity'; export { Span, SpanContext } from './span'; export { StackFrame } from './stackframe'; export { Stacktrace } from './stacktrace'; -export { Status } from './status'; export { CustomSamplingContext, Measurements, diff --git a/packages/types/src/loglevel.ts b/packages/types/src/loglevel.ts deleted file mode 100644 index 7a75d69312dc..000000000000 --- a/packages/types/src/loglevel.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** Console logging verbosity for the SDK. */ -export enum LogLevel { - /** No logs will be generated. */ - None = 0, - /** Only SDK internal errors will be logged. */ - Error = 1, - /** Information useful for debugging the SDK will be logged. */ - Debug = 2, - /** All SDK actions will be logged. */ - Verbose = 3, -} diff --git a/packages/types/src/options.ts b/packages/types/src/options.ts index f746db3412b9..eefcd225a06b 100644 --- a/packages/types/src/options.ts +++ b/packages/types/src/options.ts @@ -1,7 +1,6 @@ import { Breadcrumb, BreadcrumbHint } from './breadcrumb'; import { Event, EventHint } from './event'; import { Integration } from './integration'; -import { LogLevel } from './loglevel'; import { CaptureContext } from './scope'; import { SdkMetadata } from './sdkmetadata'; import { SamplingContext } from './transaction'; @@ -82,9 +81,6 @@ export interface Options { */ maxBreadcrumbs?: number; - /** Console logging verbosity for the SDK Client. */ - logLevel?: LogLevel; - /** A global sample rate to apply to all events (0 - 1). */ sampleRate?: number; diff --git a/packages/types/src/requestsessionstatus.ts b/packages/types/src/requestsessionstatus.ts new file mode 100644 index 000000000000..b6b7ab9ee659 --- /dev/null +++ b/packages/types/src/requestsessionstatus.ts @@ -0,0 +1,11 @@ +/** JSDoc + * @deprecated Use string literals - if you require type casting, cast to RequestSessionStatus type + */ +export enum RequestSessionStatus { + /** JSDoc */ + Ok = 'ok', + /** JSDoc */ + Errored = 'errored', + /** JSDoc */ + Crashed = 'crashed', +} diff --git a/packages/types/src/response.ts b/packages/types/src/response.ts index 3c9408f1606f..4add517f4870 100644 --- a/packages/types/src/response.ts +++ b/packages/types/src/response.ts @@ -1,10 +1,10 @@ import { Event, EventType } from './event'; +import { EventStatus } from './eventstatus'; import { Session } from './session'; -import { Status } from './status'; /** JSDoc */ export interface Response { - status: Status; + status: EventStatus; event?: Event | Session; type?: EventType; reason?: string; diff --git a/packages/types/src/scope.ts b/packages/types/src/scope.ts index c3b8f6c5b99c..00014e0735d8 100644 --- a/packages/types/src/scope.ts +++ b/packages/types/src/scope.ts @@ -4,7 +4,7 @@ import { EventProcessor } from './eventprocessor'; import { Extra, Extras } from './extra'; import { Primitive } from './misc'; import { RequestSession, Session } from './session'; -import { Severity } from './severity'; +import { SeverityLevel } from './severity'; import { Span } from './span'; import { Transaction } from './transaction'; import { User } from './user'; @@ -15,7 +15,7 @@ export type CaptureContext = Scope | Partial | ((scope: Scope) => /** JSDocs */ export interface ScopeContext { user: User; - level: Severity; + level: SeverityLevel; extra: Extras; contexts: Contexts; tags: { [key: string]: Primitive }; @@ -82,7 +82,7 @@ export interface Scope { * Sets the level on the scope for future events. * @param level string {@link Severity} */ - setLevel(level: Severity): this; + setLevel(level: SeverityLevel): this; /** * Sets the transaction name on the scope for future events. diff --git a/packages/types/src/session.ts b/packages/types/src/session.ts index 9b53772b4918..552dda002531 100644 --- a/packages/types/src/session.ts +++ b/packages/types/src/session.ts @@ -55,28 +55,8 @@ export interface SessionContext { ignoreDuration?: boolean; } -/** - * Session Status - */ -export enum SessionStatus { - /** JSDoc */ - Ok = 'ok', - /** JSDoc */ - Exited = 'exited', - /** JSDoc */ - Crashed = 'crashed', - /** JSDoc */ - Abnormal = 'abnormal', -} - -export enum RequestSessionStatus { - /** JSDoc */ - Ok = 'ok', - /** JSDoc */ - Errored = 'errored', - /** JSDoc */ - Crashed = 'crashed', -} +export type SessionStatus = 'ok' | 'exited' | 'crashed' | 'abnormal'; +export type RequestSessionStatus = 'ok' | 'errored' | 'crashed'; /** JSDoc */ export interface SessionAggregates { diff --git a/packages/types/src/sessionstatus.ts b/packages/types/src/sessionstatus.ts new file mode 100644 index 000000000000..339b4ea2f5e6 --- /dev/null +++ b/packages/types/src/sessionstatus.ts @@ -0,0 +1,13 @@ +/** JSDoc + * @deprecated Use string literals - if you require type casting, cast to SessionStatus type + */ +export enum SessionStatus { + /** JSDoc */ + Ok = 'ok', + /** JSDoc */ + Exited = 'exited', + /** JSDoc */ + Crashed = 'crashed', + /** JSDoc */ + Abnormal = 'abnormal', +} diff --git a/packages/types/src/severity.ts b/packages/types/src/severity.ts index 43f0b97cf384..688fbf261517 100644 --- a/packages/types/src/severity.ts +++ b/packages/types/src/severity.ts @@ -1,5 +1,6 @@ -/** JSDoc */ -// eslint-disable-next-line import/export +/** JSDoc + * @deprecated Use string literals - if you require type casting, cast to SeverityLevel type + */ export enum Severity { /** JSDoc */ Fatal = 'fatal', @@ -17,32 +18,5 @@ export enum Severity { Critical = 'critical', } -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -export namespace Severity { - /** - * Converts a string-based level into a {@link Severity}. - * - * @param level string representation of Severity - * @returns Severity - */ - export function fromString(level: string): Severity { - switch (level) { - case 'debug': - return Severity.Debug; - case 'info': - return Severity.Info; - case 'warn': - case 'warning': - return Severity.Warning; - case 'error': - return Severity.Error; - case 'fatal': - return Severity.Fatal; - case 'critical': - return Severity.Critical; - case 'log': - default: - return Severity.Log; - } - } -} +export const SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'] as const; +export type SeverityLevel = typeof SeverityLevels[number]; diff --git a/packages/types/src/status.ts b/packages/types/src/status.ts index 0df44d10a3f3..a80cd00b97e7 100644 --- a/packages/types/src/status.ts +++ b/packages/types/src/status.ts @@ -1,5 +1,6 @@ -/** The status of an event. */ -// eslint-disable-next-line import/export +/** JSDoc + * @deprecated Use string literals - if you require type casting, cast to EventStatus type + */ export enum Status { /** The status could not be determined. */ Unknown = 'unknown', @@ -14,32 +15,3 @@ export enum Status { /** A server-side error occurred during submission. */ Failed = 'failed', } - -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -export namespace Status { - /** - * Converts a HTTP status code into a {@link Status}. - * - * @param code The HTTP response status code. - * @returns The send status or {@link Status.Unknown}. - */ - export function fromHttpCode(code: number): Status { - if (code >= 200 && code < 300) { - return Status.Success; - } - - if (code === 429) { - return Status.RateLimit; - } - - if (code >= 400 && code < 500) { - return Status.Invalid; - } - - if (code >= 500) { - return Status.Failed; - } - - return Status.Unknown; - } -} diff --git a/packages/types/src/transaction.ts b/packages/types/src/transaction.ts index 805d1350bff0..585eb66dd8dd 100644 --- a/packages/types/src/transaction.ts +++ b/packages/types/src/transaction.ts @@ -117,15 +117,10 @@ export interface SamplingContext extends CustomSamplingContext { export type Measurements = Record; -export enum TransactionSamplingMethod { - Explicit = 'explicitly_set', - Sampler = 'client_sampler', - Rate = 'client_rate', - Inheritance = 'inheritance', -} +export type TransactionSamplingMethod = 'explicitly_set' | 'client_sampler' | 'client_rate' | 'inheritance'; export interface TransactionMetadata { - transactionSampling?: { rate?: number; method?: string }; + transactionSampling?: { rate?: number; method?: TransactionSamplingMethod }; /** The two halves (sentry and third-party) of a transaction's tracestate header, used for dynamic sampling */ tracestate?: { diff --git a/packages/types/src/transport.ts b/packages/types/src/transport.ts index 40c26c146554..a1ba2983b1a3 100644 --- a/packages/types/src/transport.ts +++ b/packages/types/src/transport.ts @@ -5,14 +5,13 @@ import { Response } from './response'; import { SdkMetadata } from './sdkmetadata'; import { Session, SessionAggregates } from './session'; -export enum Outcome { - BeforeSend = 'before_send', - EventProcessor = 'event_processor', - NetworkError = 'network_error', - QueueOverflow = 'queue_overflow', - RateLimitBackoff = 'ratelimit_backoff', - SampleRate = 'sample_rate', -} +export type Outcome = + | 'before_send' + | 'event_processor' + | 'network_error' + | 'queue_overflow' + | 'ratelimit_backoff' + | 'sample_rate'; /** Transport used sending data to Sentry */ export interface Transport { diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index ca92d86df6f0..4219bcffd61a 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -12,7 +12,9 @@ export * from './node'; export * from './object'; export * from './path'; export * from './promisebuffer'; +export * from './severity'; export * from './stacktrace'; +export * from './status'; export * from './string'; export * from './supports'; export * from './syncpromise'; diff --git a/packages/utils/src/severity.ts b/packages/utils/src/severity.ts new file mode 100644 index 000000000000..fc3ff7ef787e --- /dev/null +++ b/packages/utils/src/severity.ts @@ -0,0 +1,18 @@ +import { SeverityLevel, SeverityLevels } from '@sentry/types'; + +function isSupportedSeverity(level: string): level is SeverityLevel { + return SeverityLevels.indexOf(level as SeverityLevel) !== -1; +} +/** + * Converts a string-based level into a {@link Severity}. + * + * @param level string representation of Severity + * @returns Severity + */ +export function severityFromString(level: SeverityLevel | string): SeverityLevel { + if (level === 'warn') return 'warning'; + if (isSupportedSeverity(level)) { + return level; + } + return 'log'; +} diff --git a/packages/utils/src/status.ts b/packages/utils/src/status.ts new file mode 100644 index 000000000000..381a0971b66f --- /dev/null +++ b/packages/utils/src/status.ts @@ -0,0 +1,26 @@ +import { EventStatus } from '@sentry/types'; +/** + * Converts an HTTP status code to sentry status {@link EventStatus}. + * + * @param code number HTTP status code + * @returns EventStatus + */ +export function eventStatusFromHttpCode(code: number): EventStatus { + if (code >= 200 && code < 300) { + return 'success'; + } + + if (code === 429) { + return 'rate_limit'; + } + + if (code >= 400 && code < 500) { + return 'invalid'; + } + + if (code >= 500) { + return 'failed'; + } + + return 'unknown'; +} diff --git a/packages/utils/test/severity.test.ts b/packages/utils/test/severity.test.ts new file mode 100644 index 000000000000..8d0514e73a43 --- /dev/null +++ b/packages/utils/test/severity.test.ts @@ -0,0 +1,24 @@ +import { SeverityLevels } from '@sentry/types'; + +import { severityFromString } from '../src/severity'; + +describe('severityFromString()', () => { + describe('normalize warn and warning', () => { + test('handles warn and warning', () => { + expect(severityFromString('warn')).toBe('warning'); + expect(severityFromString('warning')).toBe('warning'); + }); + test('handles warn and warning', () => { + expect(severityFromString('warn')).toBe('warning'); + expect(severityFromString('warning')).toBe('warning'); + }); + }); + describe('default to log', () => { + expect(severityFromString('foo')).toBe('log'); + }); + describe('allows ', () => { + for (const level of SeverityLevels) { + expect(severityFromString(level)).toBe(level); + } + }); +}); diff --git a/packages/vue/src/index.bundle.ts b/packages/vue/src/index.bundle.ts index 66182044f6fd..232ec67cd0c1 100644 --- a/packages/vue/src/index.bundle.ts +++ b/packages/vue/src/index.bundle.ts @@ -3,12 +3,12 @@ export { Request, SdkInfo, Event, + EventStatus, Exception, Response, - Severity, + SeverityLevel, StackFrame, Stacktrace, - Status, Thread, User, } from '@sentry/types';