Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/effect/src/compat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { isObjectLike } from '@sentry/core';
import * as Context from 'effect/Context';
import * as Exit from 'effect/Exit';

// Check if we're running Effect v4 by checking the Exit/Cause structure
// In v4, causes have a 'reasons' array
// In v3, causes have '_tag' directly on the cause object
export const isEffectV4 = (() => {
try {
const testExit = Exit.fail('test') as unknown as { cause?: unknown };
const cause = testExit.cause;
// v4 causes have 'reasons' array, v3 causes have '_tag' directly
if (isObjectLike(cause) && 'reasons' in cause) {
return true;
}
return false;
} catch {
return false;
}
})();

interface ContextExports {
Reference: typeof Context.Reference;
/** Only Effect v3 exports it. */
GenericTag<Identifier, Service>(key: string): Context.Key<Identifier, Service>;
}

// Effect v4 has no `Context.GenericTag` and Effect v3 before 3.11 has no `Context.Reference`. Both are read
// through a separate binding because bundlers fail the build on a namespace member the installed version lacks.
// It is exported so our own build cannot fold a single use back into `Context.<member>`.
export const contextExports = Context as unknown as ContextExports;
86 changes: 48 additions & 38 deletions packages/effect/src/errorReporter.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,46 @@
import type { SeverityLevel } from '@sentry/core';
import { captureException, isObjectLike } from '@sentry/core';
import * as Effect from 'effect';
import type * as Cause from 'effect/Cause';
import * as Effect from 'effect/Effect';
import type * as EffectErrorReporter from 'effect/ErrorReporter';
import type * as EffectLayer from 'effect/Layer';
import { empty as emptyLayer } from 'effect/Layer';
import type * as LogLevel from 'effect/LogLevel';
import * as Layer from 'effect/Layer';
import { contextExports, isEffectV4 } from './compat';

// `effect/ErrorReporter` only exists in Effect v4, so it is read off the main entry instead of being imported
// as a subpath. On Effect v3 the lookup yields `undefined` and no reporter is registered. The property is read
// with `Reflect.get` because bundlers fail the build on `Effect.ErrorReporter` when the export is absent, and
// an aliased property read gets folded back into exactly that member access by our own build.
const ErrorReporter = Reflect.get(Effect, 'ErrorReporter') as typeof EffectErrorReporter | undefined;
// `effect/ErrorReporter` only exists in Effect v4. Importing it fails Effect v3 builds, and reading it off the
// `effect` main entry bundles all of Effect, so the reporter uses the string keys of that API. The types make a
// changed key fail type checking.
const TYPE_ID: EffectErrorReporter.TypeId = '~effect/ErrorReporter';
const IGNORE: EffectErrorReporter.ignore = '~effect/ErrorReporter/ignore';
const SEVERITY: EffectErrorReporter.severity = '~effect/ErrorReporter/severity';
const ATTRIBUTES: EffectErrorReporter.attributes = '~effect/ErrorReporter/attributes';

const SEVERITY_TO_LEVEL: Record<LogLevel.Severity, SeverityLevel> = {
Fatal: 'fatal',
Error: 'error',
Warn: 'warning',
Info: 'info',
Debug: 'debug',
Trace: 'debug',
};
/**
* Reference to the reporters that Effect calls for a reported failure. Effect looks up references by key, so it
* resolves to the same entry as `ErrorReporter.CurrentErrorReporters`. `undefined` on Effect v3.
*/
const CurrentErrorReporters = isEffectV4
? contextExports.Reference<ReadonlySet<EffectErrorReporter.ErrorReporter>>(
'effect/ErrorReporter/CurrentErrorReporters',
{ defaultValue: () => new Set() },
)
: undefined;

function getLevel(errorReporter: typeof EffectErrorReporter, error: unknown): SeverityLevel {
// Effect's `getSeverity` falls back to `Info` for unannotated errors, which would file plain failures as
// informational in Sentry. Only an explicit annotation changes the level.
if (isObjectLike(error) && errorReporter.severity in error) {
return SEVERITY_TO_LEVEL[errorReporter.getSeverity(error)];
}
return 'error';
}
// Only an explicit severity annotation changes the level. Effect's own `getSeverity` falls back to `Info`, which
// would file plain failures as informational in Sentry.
const SEVERITY_TO_LEVEL = new Map<unknown, SeverityLevel>([
['Fatal', 'fatal'],
['Error', 'error'],
['Warn', 'warning'],
['Info', 'info'],
['Debug', 'debug'],
['Trace', 'debug'],
]);

function makeSentryErrorReporter(errorReporter: typeof EffectErrorReporter): EffectErrorReporter.ErrorReporter {
function makeSentryErrorReporter(): EffectErrorReporter.ErrorReporter {
const reported = new WeakSet<object>();

return {
[errorReporter.TypeId]: errorReporter.TypeId,
[TYPE_ID]: TYPE_ID,
report({ cause }: { readonly cause: Cause.Cause<unknown> }): void {
if (reported.has(cause)) {
return;
Expand All @@ -52,21 +57,17 @@ function makeSentryErrorReporter(errorReporter: typeof EffectErrorReporter): Eff
const error = reason._tag === 'Fail' ? reason.error : reason.defect;

if (isObjectLike(error)) {
if (reported.has(error)) {
if (reported.has(error) || error[IGNORE] === true) {
continue;
}
reported.add(error);
}

if (errorReporter.isIgnored(error)) {
continue;
}

captureException(error, {
mechanism: { type: 'auto.function.effect.error_reporter', handled: false },
captureContext: {
level: getLevel(errorReporter, error),
extra: isObjectLike(error) ? { ...errorReporter.getAttributes(error) } : undefined,
level: (isObjectLike(error) && SEVERITY_TO_LEVEL.get(error[SEVERITY])) || 'error',
extra: isObjectLike(error) ? { ...(error[ATTRIBUTES] as Record<string, unknown> | undefined) } : undefined,
},
});
}
Expand All @@ -80,10 +81,19 @@ function makeSentryErrorReporter(errorReporter: typeof EffectErrorReporter): Eff
*
* Effect v3 has no `ErrorReporter` API, so the returned layer is empty there.
*/
export function makeSentryErrorReporterLayer(): EffectLayer.Layer<never, never, never> {
if (!ErrorReporter) {
return emptyLayer;
export function makeSentryErrorReporterLayer(): Layer.Layer<never> {
if (!CurrentErrorReporters) {
return Layer.empty;
}

return ErrorReporter.layer([makeSentryErrorReporter(ErrorReporter)], { mergeWithExisting: true });
const sentryErrorReporter = makeSentryErrorReporter();

return Layer.effect(
CurrentErrorReporters,
Effect.gen(function* () {
const reporters = new Set(yield* CurrentErrorReporters);
reporters.add(sentryErrorReporter);
return reporters;
}),
);
}
28 changes: 1 addition & 27 deletions packages/effect/src/tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type * as EffectLayer from 'effect/Layer';
import { succeed as succeedLayer } from 'effect/Layer';
import * as Option from 'effect/Option';
import * as EffectTracer from 'effect/Tracer';
import { contextExports, isEffectV4 } from './compat';

const EFFECT_SPAN_SYMBOL = Symbol.for('@sentry/effect.EffectSpan');

Expand Down Expand Up @@ -213,35 +214,8 @@ class SentrySpanWrapper implements SentrySpanLike {
*/
export type StartInactiveSpan = (options: StartSpanOptions) => Span;

// Check if we're running Effect v4 by checking the Exit/Cause structure
// In v4, causes have a 'reasons' array
// In v3, causes have '_tag' directly on the cause object
const isEffectV4 = (() => {
try {
const testExit = Exit.fail('test') as unknown as { cause?: unknown };
const cause = testExit.cause;
// v4 causes have 'reasons' array, v3 causes have '_tag' directly
if (isObjectLike(cause) && 'reasons' in cause) {
return true;
}
return false;
} catch {
return false;
}
})();

const EXTERNAL_SPAN_KEY = '@sentry/effect/ExternalSpan';

interface ContextExports {
Reference: typeof Context.Reference;
/** Only Effect v3 exports it. */
GenericTag<Identifier, Service>(key: string): Context.Key<Identifier, Service>;
}

// Effect v4 has no `Context.GenericTag` and Effect v3 before 3.11 has no `Context.Reference`. Both are read
// through a separate binding because bundlers fail the build on a namespace member the installed version lacks.
const contextExports = Context as unknown as ContextExports;

/**
* Whether the tracer continues the trace of a `Tracer.externalSpan` parent. Effect v4 has no `FiberRef`
* and v3 before 3.11 has no `Context.Reference`, so the flag is a plain service in both. The cast is safe:
Expand Down
16 changes: 8 additions & 8 deletions packages/effect/test/errorReporter-v3.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { getMainCarrier } from '@sentry/core';
import type * as EffectModule from 'effect';
import { Effect, Layer } from 'effect';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as Compat from '../src/compat';
import { makeSentryErrorReporterLayer } from '../src/errorReporter';
import * as sentryServer from '../src/index.server';
import { effectLayer } from '../src/server/index';

// Effect v3 ships no `ErrorReporter` module, so its main entry has no such namespace.
vi.mock('effect', async importOriginal => {
const actual = await importOriginal<typeof EffectModule>();
return { ...actual, ErrorReporter: undefined };
});
// Effect v3 ships no `ErrorReporter` API.
vi.mock('../src/compat', async importOriginal => ({
...(await importOriginal<typeof Compat>()),
isEffectV4: false,
}));

describe('Sentry ErrorReporter without the Effect v4 ErrorReporter API', () => {
beforeEach(() => {
Expand All @@ -24,7 +24,7 @@ describe('Sentry ErrorReporter without the Effect v4 ErrorReporter API', () => {
const result = await Effect.runPromise(
Effect.succeed('ok').pipe(
Effect.provide(
sentryServer.effectLayer({
effectLayer({
dsn: 'https://username@domain/123',
transport: () => ({
send: vi.fn().mockResolvedValue({}),
Expand Down
Loading