Skip to content

Commit

Permalink
ref: Hoist flush, close, and lastEventId into @sentry/core (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lforst authored Aug 4, 2023
1 parent 436fdeb commit b9a1c2b
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 113 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ jobs:
needs: [job_get_metadata, job_build]
if: needs.job_get_metadata.outputs.changed_browser == 'true' || github.event_name != 'pull_request'
runs-on: ubuntu-20.04
timeout-minutes: 10
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
Expand Down
16 changes: 4 additions & 12 deletions packages/browser/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ export {
captureException,
captureEvent,
captureMessage,
close,
configureScope,
createTransport,
flush,
getHubFromCarrier,
getCurrentHub,
Hub,
lastEventId,
makeMain,
Scope,
startTransaction,
Expand Down Expand Up @@ -60,16 +63,5 @@ export {
} from './stack-parsers';
export { eventFromException, eventFromMessage } from './eventbuilder';
export { createUserFeedbackEnvelope } from './userfeedback';
export {
defaultIntegrations,
forceLoad,
init,
lastEventId,
onLoad,
showReportDialog,
flush,
close,
wrap,
captureUserFeedback,
} from './sdk';
export { defaultIntegrations, forceLoad, init, onLoad, showReportDialog, wrap, captureUserFeedback } from './sdk';
export { GlobalHandlers, TryCatch, Breadcrumbs, LinkedErrors, HttpContext, Dedupe } from './integrations';
51 changes: 1 addition & 50 deletions packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,7 @@ import {
Integrations as CoreIntegrations,
} from '@sentry/core';
import type { UserFeedback } from '@sentry/types';
import {
addInstrumentationHandler,
logger,
resolvedSyncPromise,
stackParserFromStackParserOptions,
supportsFetch,
} from '@sentry/utils';
import { addInstrumentationHandler, logger, stackParserFromStackParserOptions, supportsFetch } from '@sentry/utils';

import type { BrowserClientOptions, BrowserOptions } from './client';
import { BrowserClient } from './client';
Expand Down Expand Up @@ -179,15 +173,6 @@ export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = g
}
}

/**
* This is the getter for lastEventId.
*
* @returns The last event id of a captured event.
*/
export function lastEventId(): string | undefined {
return getCurrentHub().lastEventId();
}

/**
* This function is here to be API compatible with the loader.
* @hidden
Expand All @@ -204,40 +189,6 @@ export function onLoad(callback: () => void): void {
callback();
}

/**
* Call `flush()` on the current client, if there is one. See {@link Client.flush}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
* the client to wait until all events are sent before resolving the promise.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export function flush(timeout?: number): PromiseLike<boolean> {
const client = getCurrentHub().getClient<BrowserClient>();
if (client) {
return client.flush(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');
return resolvedSyncPromise(false);
}

/**
* Call `close()` on the current client, if there is one. See {@link Client.close}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
* parameter will cause the client to wait until all events are sent before disabling itself.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export function close(timeout?: number): PromiseLike<boolean> {
const client = getCurrentHub().getClient<BrowserClient>();
if (client) {
return client.close(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');
return resolvedSyncPromise(false);
}

/**
* Wrap code within a try/catch block so the SDK is able to capture errors.
*
Expand Down
43 changes: 43 additions & 0 deletions packages/core/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,46 @@ export function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorCo

return uuid4();
}

/**
* Call `flush()` on the current client, if there is one. See {@link Client.flush}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
* the client to wait until all events are sent before resolving the promise.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export async function flush(timeout?: number): Promise<boolean> {
const client = getCurrentHub().getClient();
if (client) {
return client.flush(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');
return Promise.resolve(false);
}

/**
* Call `close()` on the current client, if there is one. See {@link Client.close}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
* parameter will cause the client to wait until all events are sent before disabling itself.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export async function close(timeout?: number): Promise<boolean> {
const client = getCurrentHub().getClient();
if (client) {
return client.close(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');
return Promise.resolve(false);
}

/**
* This is the getter for lastEventId.
*
* @returns The last event id of a captured event.
*/
export function lastEventId(): string | undefined {
return getCurrentHub().lastEventId();
}
5 changes: 4 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ export type { OfflineStore, OfflineTransportOptions } from './transports/offline
export * from './tracing';
export {
addBreadcrumb,
captureCheckIn,
captureException,
captureEvent,
captureMessage,
close,
configureScope,
flush,
lastEventId,
startTransaction,
setContext,
setExtra,
Expand All @@ -17,7 +21,6 @@ export {
setTags,
setUser,
withScope,
captureCheckIn,
} from './exports';
export {
getCurrentHub,
Expand Down
3 changes: 2 additions & 1 deletion packages/node/src/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
captureException,
flush,
getCurrentHub,
hasTracingEnabled,
runWithAsyncContext,
Expand All @@ -25,7 +26,7 @@ import type { NodeClient } from './client';
import { extractRequestData } from './requestdata';
// TODO (v8 / XXX) Remove this import
import type { ParseRequestOptions } from './requestDataDeprecated';
import { flush, isAutoSessionTrackingEnabled } from './sdk';
import { isAutoSessionTrackingEnabled } from './sdk';

/**
* Express-compatible tracing handler.
Expand Down
5 changes: 4 additions & 1 deletion packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,16 @@ export {
captureException,
captureEvent,
captureMessage,
close,
configureScope,
createTransport,
extractTraceparentData,
flush,
getActiveTransaction,
getHubFromCarrier,
getCurrentHub,
Hub,
lastEventId,
makeMain,
runWithAsyncContext,
Scope,
Expand All @@ -57,7 +60,7 @@ export { autoDiscoverNodePerformanceMonitoringIntegrations } from './tracing';

export { NodeClient } from './client';
export { makeNodeTransport } from './transports';
export { defaultIntegrations, init, defaultStackParser, lastEventId, flush, close, getSentryRelease } from './sdk';
export { defaultIntegrations, init, defaultStackParser, getSentryRelease } from './sdk';
export { addRequestDataToEvent, DEFAULT_USER_INCLUDES, extractRequestData } from './requestdata';
export { deepReadDirSync } from './utils';
export { getModuleFromFilename } from './module';
Expand Down
44 changes: 0 additions & 44 deletions packages/node/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type { SessionStatus, StackParser } from '@sentry/types';
import {
createStackParser,
GLOBAL_OBJ,
logger,
nodeStackLineParser,
stackParserFromStackParserOptions,
tracingContextFromHeaders,
Expand Down Expand Up @@ -177,49 +176,6 @@ export function init(options: NodeOptions = {}): void {
updateScopeFromEnvVariables();
}

/**
* This is the getter for lastEventId.
*
* @returns The last event id of a captured event.
*/
export function lastEventId(): string | undefined {
return getCurrentHub().lastEventId();
}

/**
* Call `flush()` on the current client, if there is one. See {@link Client.flush}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
* the client to wait until all events are sent before resolving the promise.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export async function flush(timeout?: number): Promise<boolean> {
const client = getCurrentHub().getClient<NodeClient>();
if (client) {
return client.flush(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');
return Promise.resolve(false);
}

/**
* Call `close()` on the current client, if there is one. See {@link Client.close}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
* parameter will cause the client to wait until all events are sent before disabling itself.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export async function close(timeout?: number): Promise<boolean> {
const client = getCurrentHub().getClient<NodeClient>();
if (client) {
return client.close(timeout);
}
__DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');
return Promise.resolve(false);
}

/**
* Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client
*/
Expand Down
5 changes: 2 additions & 3 deletions packages/node/test/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import * as http from 'http';

import { NodeClient } from '../src/client';
import { errorHandler, requestHandler, tracingHandler } from '../src/handlers';
import * as SDK from '../src/sdk';
import { getDefaultNodeClientOptions } from './helper/node-client-options';

function mockAsyncContextStrategy(getHub: () => Hub): void {
Expand Down Expand Up @@ -128,7 +127,7 @@ describe('requestHandler', () => {
});

it('patches `res.end` when `flushTimeout` is specified', done => {
const flush = jest.spyOn(SDK, 'flush').mockResolvedValue(true);
const flush = jest.spyOn(sentryCore, 'flush').mockResolvedValue(true);

const sentryRequestMiddleware = requestHandler({ flushTimeout: 1337 });
sentryRequestMiddleware(req, res, next);
Expand All @@ -142,7 +141,7 @@ describe('requestHandler', () => {
});

it('prevents errors thrown during `flush` from breaking the response', done => {
jest.spyOn(SDK, 'flush').mockRejectedValue(new SentryError('HTTP Error (429)'));
jest.spyOn(sentryCore, 'flush').mockRejectedValue(new SentryError('HTTP Error (429)'));

const sentryRequestMiddleware = requestHandler({ flushTimeout: 1337 });
sentryRequestMiddleware(req, res, next);
Expand Down

0 comments on commit b9a1c2b

Please sign in to comment.