-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(remix): Add Remix server SDK #5269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
/* | ||
* This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking | ||
* for users. | ||
* | ||
* Debug flags need to be declared in each package individually and must not be imported across package boundaries, | ||
* because some build tools have trouble tree-shaking imported guards. | ||
* | ||
* As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder. | ||
* | ||
* Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during | ||
* our, or the user's build process. Take care when introducing new flags - they must not throw if they are not | ||
* replaced. | ||
*/ | ||
|
||
declare const __SENTRY_DEBUG__: boolean; | ||
|
||
/** Flag that is true for debug builds, false otherwise. */ | ||
export const IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can remove this file. Please see https://github.com/getsentry/sentry-javascript/blob/master/CONTRIBUTING.md#debug-build-flags for more details. We should just be able to use |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
/* eslint-disable import/export */ | ||
import { configureScope, getCurrentHub, init as nodeInit } from '@sentry/node'; | ||
|
||
import { instrumentServer } from './utils/instrumentServer'; | ||
import { buildMetadata } from './utils/metadata'; | ||
import { RemixOptions } from './utils/remixOptions'; | ||
|
||
function sdkAlreadyInitialized(): boolean { | ||
const hub = getCurrentHub(); | ||
return !!hub.getClient(); | ||
} | ||
|
||
/** Initializes Sentry Remix SDK on Node. */ | ||
export function init(options: RemixOptions): void { | ||
buildMetadata(options, ['remix', 'node']); | ||
|
||
if (sdkAlreadyInitialized()) { | ||
// TODO: Log something | ||
return; | ||
AbhiPrasad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
instrumentServer(); | ||
|
||
nodeInit(options); | ||
|
||
configureScope(scope => { | ||
scope.setTag('runtime', 'node'); | ||
}); | ||
} | ||
|
||
export { ErrorBoundary, withErrorBoundary } from '@sentry/react'; | ||
export { remixRouterInstrumentation, withSentryRouteTracing } from './performance/client'; | ||
export { BrowserTracing, Integrations } from '@sentry/tracing'; | ||
export * from '@sentry/node'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. let's move these exports to the top |
This file was deleted.
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
@@ -0,0 +1,195 @@ | ||||
import { captureException, configureScope, getCurrentHub, startTransaction } from '@sentry/node'; | ||||
import { getActiveTransaction, hasTracingEnabled } from '@sentry/tracing'; | ||||
import { addExceptionMechanism, fill, loadModule, logger } from '@sentry/utils'; | ||||
|
||||
import { IS_DEBUG_BUILD } from '../flags'; | ||||
|
||||
type AppLoadContext = unknown; | ||||
type AppData = unknown; | ||||
type RequestHandler = (request: Request, loadContext?: AppLoadContext) => Promise<Response>; | ||||
type CreateRequestHandlerFunction = (build: ServerBuild, mode?: string) => RequestHandler; | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are these all vendored in? Can we link to the code + git sha where we did this? |
||||
type ServerRouteManifest = RouteManifest<Omit<ServerRoute, 'children'>>; | ||||
type Params<Key extends string = string> = { | ||||
readonly [key in Key]: string | undefined; | ||||
}; | ||||
|
||||
interface Route { | ||||
index?: boolean; | ||||
caseSensitive?: boolean; | ||||
id: string; | ||||
parentId?: string; | ||||
path?: string; | ||||
} | ||||
|
||||
interface ServerRouteModule { | ||||
action?: DataFunction; | ||||
headers?: unknown; | ||||
loader?: DataFunction; | ||||
} | ||||
|
||||
interface ServerRoute extends Route { | ||||
children: ServerRoute[]; | ||||
module: ServerRouteModule; | ||||
} | ||||
|
||||
interface RouteManifest<Route> { | ||||
[routeId: string]: Route; | ||||
} | ||||
|
||||
interface ServerBuild { | ||||
entry: { | ||||
module: ServerEntryModule; | ||||
}; | ||||
routes: ServerRouteManifest; | ||||
assets: unknown; | ||||
} | ||||
|
||||
interface HandleDocumentRequestFunction { | ||||
(request: Request, responseStatusCode: number, responseHeaders: Headers, context: Record<symbol, unknown>): | ||||
| Promise<Response> | ||||
| Response; | ||||
} | ||||
|
||||
interface HandleDataRequestFunction { | ||||
(response: Response, args: DataFunctionArgs): Promise<Response> | Response; | ||||
} | ||||
|
||||
interface ServerEntryModule { | ||||
default: HandleDocumentRequestFunction; | ||||
handleDataRequest?: HandleDataRequestFunction; | ||||
} | ||||
|
||||
interface DataFunctionArgs { | ||||
request: Request; | ||||
context: AppLoadContext; | ||||
params: Params; | ||||
} | ||||
|
||||
interface DataFunction { | ||||
(args: DataFunctionArgs): Promise<Response> | Response | Promise<AppData> | AppData; | ||||
} | ||||
|
||||
function makeWrappedDataFunction(origFn: DataFunction, name: 'action' | 'loader'): DataFunction { | ||||
return async function (this: unknown, args: DataFunctionArgs): Promise<Response | AppData> { | ||||
let res: Response | AppData; | ||||
const activeTransaction = getActiveTransaction(); | ||||
const currentScope = getCurrentHub().getScope(); | ||||
|
||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of using optional chaining, let's just early return if there is no |
||||
try { | ||||
const span = activeTransaction?.startChild({ | ||||
op: `remix.server.${name}`, | ||||
description: activeTransaction.name, | ||||
tags: { | ||||
name, | ||||
}, | ||||
}); | ||||
|
||||
if (span) { | ||||
// Assign data function to hub to be able to see `db` transactions (if any) as children. | ||||
currentScope?.setSpan(span); | ||||
} | ||||
|
||||
res = await origFn.call(this, args); | ||||
span?.finish(); | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we re-add back the transaction onto the scope? currentScope.setSpan(activeTransaction);
span.finish(); There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is optional chaining still needed here? |
||||
} catch (err) { | ||||
configureScope(scope => { | ||||
scope.addEventProcessor(event => { | ||||
addExceptionMechanism(event, { | ||||
type: 'instrument', | ||||
handled: true, | ||||
data: { | ||||
function: name, | ||||
}, | ||||
}); | ||||
|
||||
return event; | ||||
}); | ||||
}); | ||||
|
||||
captureException(err); | ||||
|
||||
// Rethrow for other handlers | ||||
throw err; | ||||
} | ||||
|
||||
return res; | ||||
}; | ||||
} | ||||
|
||||
function makeWrappedAction(origAction: DataFunction): DataFunction { | ||||
return makeWrappedDataFunction(origAction, 'action'); | ||||
} | ||||
|
||||
function makeWrappedLoader(origAction: DataFunction): DataFunction { | ||||
return makeWrappedDataFunction(origAction, 'loader'); | ||||
} | ||||
|
||||
function wrapRequestHandler(origRequestHandler: RequestHandler): RequestHandler { | ||||
return async function (this: unknown, request: Request, loadContext?: unknown): Promise<Response> { | ||||
const currentScope = getCurrentHub().getScope(); | ||||
|
||||
// debugger; | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||
const transaction = hasTracingEnabled() | ||||
? startTransaction({ | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||
name: request.url, | ||||
op: 'remix.server.requesthandler', | ||||
tags: { | ||||
method: request.method, | ||||
}, | ||||
}) | ||||
: undefined; | ||||
|
||||
if (transaction) { | ||||
currentScope?.setSpan(transaction); | ||||
} | ||||
|
||||
const res = (await origRequestHandler.call(this, request, loadContext)) as Response; | ||||
|
||||
transaction?.setHttpStatus(res.status); | ||||
transaction?.finish(); | ||||
|
||||
return res; | ||||
}; | ||||
} | ||||
|
||||
function makeWrappedCreateRequestHandler( | ||||
origCreateRequestHandler: CreateRequestHandlerFunction, | ||||
): CreateRequestHandlerFunction { | ||||
return function (this: unknown, build: ServerBuild, mode: string | undefined): RequestHandler { | ||||
const routes: ServerRouteManifest = {}; | ||||
|
||||
for (const [id, route] of Object.entries(build.routes)) { | ||||
const wrappedRoute = { ...route, module: { ...route.module } }; | ||||
|
||||
if (wrappedRoute.module.action) { | ||||
fill(wrappedRoute.module, 'action', makeWrappedAction); | ||||
} | ||||
|
||||
if (wrappedRoute.module.loader) { | ||||
fill(wrappedRoute.module, 'loader', makeWrappedLoader); | ||||
} | ||||
|
||||
routes[id] = wrappedRoute; | ||||
} | ||||
|
||||
const requestHandler = origCreateRequestHandler.call(this, { ...build, routes }, mode); | ||||
|
||||
return wrapRequestHandler(requestHandler); | ||||
}; | ||||
} | ||||
|
||||
/** | ||||
* Monkey-patch Remix's `createRequestHandler` from `@remix-run/server-runtime` | ||||
* which Remix Adapters (https://remix.run/docs/en/v1/api/remix) use underneath. | ||||
*/ | ||||
export function instrumentServer(): void { | ||||
const pkg = loadModule<{ createRequestHandler: CreateRequestHandlerFunction }>('@remix-run/server-runtime'); | ||||
|
||||
if (!pkg) { | ||||
IS_DEBUG_BUILD && logger.warn('Remix SDK was unable to require `@remix-run/server-runtime` package.'); | ||||
|
||||
return; | ||||
} | ||||
|
||||
fill(pkg, 'createRequestHandler', makeWrappedCreateRequestHandler); | ||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import { NodeOptions } from '@sentry/node'; | ||
import { BrowserOptions } from '@sentry/react'; | ||
import { Options } from '@sentry/types'; | ||
|
||
export type RemixOptions = Options | BrowserOptions; | ||
export type RemixOptions = Options | BrowserOptions | NodeOptions; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import * as SentryNode from '@sentry/node'; | ||
import { getCurrentHub } from '@sentry/node'; | ||
import { getGlobalObject } from '@sentry/utils'; | ||
|
||
import { init } from '../src/index.server'; | ||
|
||
const global = getGlobalObject(); | ||
|
||
const nodeInit = jest.spyOn(SentryNode, 'init'); | ||
|
||
describe('Server init()', () => { | ||
afterEach(() => { | ||
jest.clearAllMocks(); | ||
global.__SENTRY__.hub = undefined; | ||
}); | ||
|
||
it('inits the Node SDK', () => { | ||
expect(nodeInit).toHaveBeenCalledTimes(0); | ||
init({}); | ||
expect(nodeInit).toHaveBeenCalledTimes(1); | ||
expect(nodeInit).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
_metadata: { | ||
sdk: { | ||
name: 'sentry.javascript.remix', | ||
version: expect.any(String), | ||
packages: [ | ||
{ | ||
name: 'npm:@sentry/remix', | ||
version: expect.any(String), | ||
}, | ||
{ | ||
name: 'npm:@sentry/node', | ||
version: expect.any(String), | ||
}, | ||
], | ||
}, | ||
}, | ||
}), | ||
); | ||
}); | ||
|
||
it("doesn't reinitialize the node SDK if already initialized", () => { | ||
expect(nodeInit).toHaveBeenCalledTimes(0); | ||
init({}); | ||
expect(nodeInit).toHaveBeenCalledTimes(1); | ||
init({}); | ||
expect(nodeInit).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
it('sets runtime on scope', () => { | ||
const currentScope = getCurrentHub().getScope(); | ||
|
||
// @ts-ignore need access to protected _tags attribute | ||
expect(currentScope._tags).toEqual({}); | ||
|
||
init({}); | ||
|
||
// @ts-ignore need access to protected _tags attribute | ||
expect(currentScope._tags).toEqual({ runtime: 'node' }); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do these have side effects?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I took that from Next.JS SDK.
As I understand, we need to export browser / react stuff from
index.server.ts
to make TypeScript happy on compile time, but it's not guaranteed that it'll be used on runtime. (index.client.ts
is used instead on the demo project).So my guess is that flagging
index.server.*
as side effects is to prevent a pre-bundler that may fail TS compilation.